Calling superclass constructor with super or just setTitle? - java

What is the recommended method of setting the title with setTitle("Title")or super("Title") while extending javax.swing.JFrame in terms of performance?

If you grepcode JFrame (in OpenJDK 6-b14), and dig a bit, you see that the constructor JFrame() calls the constructor Frame(), which calls Frame("") (link).
So, since an implicit super() is added if you don't specify a call to any super constructor yourself, it would be (although very slightly so) more effective to call super("Title").

If you're in your constructor, try to delegate as much functionality as possible to the super constructor. It's possible that you can save it from doing some work.
For instance, the default super constructor might create some inner objects that will just get overwritten when you call the setter. If you pass the correct data immediately, you give it the opportunity to be more efficient.
But I think in this specific case, it does not matter much.

It is a good practice to always call the corresponding super(.....) when you extend a class.
As you never know what magic the super constructor does behind the scene.
You never need just
call super();
That's what will be there if you don't specify anything else. You only need to specify the constructor to call if:
You want to call a superclass constructor which has parameters
You want to chain to another constructor in the same class instead of the superclass constructor

Related

When is it absolutely necessary to make an explicit call to superclass' parameterized constructors and why so?

In other words,
If a superclass does not have a default constructor, any subclasses extending it must make an explicit call to one of the superclass' parameterized constructors. why so?
It would be nice if you could try explaining it using Java.
Assume that your superclass has a field something and a constructor which initializes that field based on a passed parameter. You cannot create a child instance without properly initializing the super class. And if there is no default constructor the compiler cannot implicitly make the call. Instead it now it needs a parameter value to pass and the compiler cannot figure that value out on its own, instead you as the programmer need to explicitly state which parameter to pass to what super constructor.

Which overridden methods should have a call to super and where? [duplicate]

Sometimes when I override methods, I get an exception the first time it's called like below:
05-31 21:32:04.266: E/AndroidRuntime(28471): android.support.v4.app.SuperNotCalledException:
Fragment AnalFragment{41795860 #1 id=0x7f070002} did not call through to super.onDestroy()
Why are we forced to call super.method()? It makes sense that there are obligations by the parent class, but more importantly, how do we know that a method requires super to be called, rather than waiting for it to crash?
Why are we forced to call super.method()?
The classes that make up the Android SDK can be incredibly complex. For instance, both activities and fragments must perform a number of operations in order to function properly (i.e. managing life cycle, optimizing memory usage, drawing the layout to the screen, etc.). Requiring the client to make a call to the base class (often at the beginning of the method) ensures that these operations are still performed, while still providing a reasonable level of abstraction for the developer.
How do we know that a function method requires super to be called?
The documentation should tell you whether or not this is required. If it doesn't I'd Google-search for some sample code (or check the API demos... or better yet, look at the source code!). It shouldn't be too difficult to figure out.
I know this is not the true intention of the OP, he did ask this question and I don't believe it got a very good answer so, if anybody is ever wondering "Why the heck do I HAVE to call super?!? If they're going to require it, why don't they just do it for me!!!". Here's the answer to that questions....
Basically, super() is something that must be called if you're overriding something that MUST be called, which can often be rather complicated code. Now, the reason they don't just do it for you and call it before your function is mostly so that you have control! :-D
To be more specific, you cannot control IF you call super(), however, you can control WHEN!
So, let's say you have some specific code that needs to happen BEFORE super() gets called, you now have the freedom to call super() only after running your code. Or... let's say you require super() to have already ran for your code not to crash, you now have the option to run super() before running your code, hence ensuring that everything is set up for you. Heck, you could even technically override the superclass hardcore and code your own method that takes care of super() itself, and make it so you don't have to call super(), but 99.9% of the time sane people will not need to do this! :-P
So, the short answer to "why do I have to call super()" is... So that you can control when it's called and do things before, or after super() gets ran. :-)
The super keyword has two main uses
1. Calls the superclass’ constructor.
2. Access a member of the superclass that has been hidden by a member of a subclass.
So, why need to user super keyword sometimes ? Answer would be android comes under 4GL language which means it has many functionality ready made. While we are overridding these methods for the customization we use super keyword.
see the very simple usage of super keyword in android ( as we do it most of the time ).
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.
.
.
}
super() must always be the first statement executed inside a subclass’ constructor. When a subclass calls super(), it is calling the constructor of its immediate superclass. The second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.
The requirement is generally specified directly in the API documentation. For example, see android.widget.ListView.onFinishInflate:
protected void onFinishInflate ()
...
Even if the subclass overrides onFinishInflate, they should always be sure to call the super method, so that we get called.
Unfortunately, my personal experience is that Android docs are uneven in quality. So, I suspect there are cases where the call is required but not documented as such.
It is important to note that once you override a method, you basically ignore everything that was in the parent class and instead have your own custom implementation in the child class (literally overwriting it)!
In our case, we don't want to throw away the parent implementation. We actually want to continue to use the original method, and ADD the extra checks for each child class individually.
This is where we get to use the "super" keyword!
You are allowed to re-use the parent method in the child class by using the "super" keyword, followed by a dot and then the method name:
for example: isValidMove(position) is method for chess pieces & check move validity & bound in the 8x8 chess board.
super.isValidMove(position);
Using the keyword super here means that we want to run the actual method in the super (or parent) class from inside the implementation in "this" class.
Which means in each of the child classes, before you get to check the custom movement, you can check if super.isValidMove(position) has returned false. If so, then no need to do any more checks and immediately return false; otherwise, continue checking.
The new implementation for the Rook class will look like this:
class Rook extends Piece{
boolean isValidMove(Position newPosition){
// First call the parent's method to check for the board bounds
if(!super.isValidMove(position)){
return false;
}
// If we passed the first test then check for the specific rock movement
if(newPosition.column == this.column && newPosition.row == this.row){
return true;
}
else{
return false;
}
}
}
You can also use super() to call the parent's constructor. This is usually done when implementing the child's constructor. Typically you would want to first run everything in the parent's constructor then add more code in the child's constructor:
class Rook extends Piece{
// default constructor
public Rook(){
super(); // this will call the parent's constructor
this.name = "rook";
}
}
Note: If a child's constructor does not explicitly call the parent's constructor using super, the Java compiler automatically inserts a call to the default constructor of the parent class. If the parent class does not have a default constructor, you will get a compile-time error.
As a basic, super is a method used to refer the main superclass field/method from which class extension is done(using extends in the initial class definition) or whose instance is created from.
When we need a most basic definition to be altered of the method/field of the superclass to be used to solve our purpose.
for example
java.lang.Object (has a lot of methods & fields) >android.view.View >android.view.ViewGroup >android.widget.LinearLayout
But if you need to change/use as it is a method of the Object Class then you need the Super method to refer the first time created method in the object class within
the LinearLayout class.

making a subClass do something whenever any of the super class' constructor is called

I want to extend JPanel.
class VisiblePanel extends JPanel{
}
How can I make VisiblePanel call setVisible(true); whenever it is instanciated, without overriding all of the constructors one by one?
by providing default constructor which invokes this.setVisible(true); and making sure if you overload constructor you still take care of it
I'm combining the Jigar Joshi's answer and DaaaahWhoosh's comment and adding it some more.
Super class constructors are not inherited so there is no way to call super class constructors. (Java Constructor Inheritance)
So the best way of doing it would be creating a default(without parameters) constructor that does the desired action and calling it from other constructors. If default constructor is required to do something that other constructors shouldn't, creating an initialization method and calling it from every constructor is the way to go.

Why do we have to call super in Android sometimes?

Sometimes when I override methods, I get an exception the first time it's called like below:
05-31 21:32:04.266: E/AndroidRuntime(28471): android.support.v4.app.SuperNotCalledException:
Fragment AnalFragment{41795860 #1 id=0x7f070002} did not call through to super.onDestroy()
Why are we forced to call super.method()? It makes sense that there are obligations by the parent class, but more importantly, how do we know that a method requires super to be called, rather than waiting for it to crash?
Why are we forced to call super.method()?
The classes that make up the Android SDK can be incredibly complex. For instance, both activities and fragments must perform a number of operations in order to function properly (i.e. managing life cycle, optimizing memory usage, drawing the layout to the screen, etc.). Requiring the client to make a call to the base class (often at the beginning of the method) ensures that these operations are still performed, while still providing a reasonable level of abstraction for the developer.
How do we know that a function method requires super to be called?
The documentation should tell you whether or not this is required. If it doesn't I'd Google-search for some sample code (or check the API demos... or better yet, look at the source code!). It shouldn't be too difficult to figure out.
I know this is not the true intention of the OP, he did ask this question and I don't believe it got a very good answer so, if anybody is ever wondering "Why the heck do I HAVE to call super?!? If they're going to require it, why don't they just do it for me!!!". Here's the answer to that questions....
Basically, super() is something that must be called if you're overriding something that MUST be called, which can often be rather complicated code. Now, the reason they don't just do it for you and call it before your function is mostly so that you have control! :-D
To be more specific, you cannot control IF you call super(), however, you can control WHEN!
So, let's say you have some specific code that needs to happen BEFORE super() gets called, you now have the freedom to call super() only after running your code. Or... let's say you require super() to have already ran for your code not to crash, you now have the option to run super() before running your code, hence ensuring that everything is set up for you. Heck, you could even technically override the superclass hardcore and code your own method that takes care of super() itself, and make it so you don't have to call super(), but 99.9% of the time sane people will not need to do this! :-P
So, the short answer to "why do I have to call super()" is... So that you can control when it's called and do things before, or after super() gets ran. :-)
The super keyword has two main uses
1. Calls the superclass’ constructor.
2. Access a member of the superclass that has been hidden by a member of a subclass.
So, why need to user super keyword sometimes ? Answer would be android comes under 4GL language which means it has many functionality ready made. While we are overridding these methods for the customization we use super keyword.
see the very simple usage of super keyword in android ( as we do it most of the time ).
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.
.
.
}
super() must always be the first statement executed inside a subclass’ constructor. When a subclass calls super(), it is calling the constructor of its immediate superclass. The second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.
The requirement is generally specified directly in the API documentation. For example, see android.widget.ListView.onFinishInflate:
protected void onFinishInflate ()
...
Even if the subclass overrides onFinishInflate, they should always be sure to call the super method, so that we get called.
Unfortunately, my personal experience is that Android docs are uneven in quality. So, I suspect there are cases where the call is required but not documented as such.
It is important to note that once you override a method, you basically ignore everything that was in the parent class and instead have your own custom implementation in the child class (literally overwriting it)!
In our case, we don't want to throw away the parent implementation. We actually want to continue to use the original method, and ADD the extra checks for each child class individually.
This is where we get to use the "super" keyword!
You are allowed to re-use the parent method in the child class by using the "super" keyword, followed by a dot and then the method name:
for example: isValidMove(position) is method for chess pieces & check move validity & bound in the 8x8 chess board.
super.isValidMove(position);
Using the keyword super here means that we want to run the actual method in the super (or parent) class from inside the implementation in "this" class.
Which means in each of the child classes, before you get to check the custom movement, you can check if super.isValidMove(position) has returned false. If so, then no need to do any more checks and immediately return false; otherwise, continue checking.
The new implementation for the Rook class will look like this:
class Rook extends Piece{
boolean isValidMove(Position newPosition){
// First call the parent's method to check for the board bounds
if(!super.isValidMove(position)){
return false;
}
// If we passed the first test then check for the specific rock movement
if(newPosition.column == this.column && newPosition.row == this.row){
return true;
}
else{
return false;
}
}
}
You can also use super() to call the parent's constructor. This is usually done when implementing the child's constructor. Typically you would want to first run everything in the parent's constructor then add more code in the child's constructor:
class Rook extends Piece{
// default constructor
public Rook(){
super(); // this will call the parent's constructor
this.name = "rook";
}
}
Note: If a child's constructor does not explicitly call the parent's constructor using super, the Java compiler automatically inserts a call to the default constructor of the parent class. If the parent class does not have a default constructor, you will get a compile-time error.
As a basic, super is a method used to refer the main superclass field/method from which class extension is done(using extends in the initial class definition) or whose instance is created from.
When we need a most basic definition to be altered of the method/field of the superclass to be used to solve our purpose.
for example
java.lang.Object (has a lot of methods & fields) >android.view.View >android.view.ViewGroup >android.widget.LinearLayout
But if you need to change/use as it is a method of the Object Class then you need the Super method to refer the first time created method in the object class within
the LinearLayout class.

Cannot find constructor File() in java.io.File

This is probably obvious, so bear with me.
YES, I KNOW THAT java.io.File has no default constructor.
The problem is that When I try to extend java.io.File, it says "Cannot find constructor File() in java.io.File" even though I am overriding the default constructor in java.lang.Object.
Here is my code:
AbsRelFile.java
import java.io.File;
public class AbsRelFile extends File {
File f;
private AbsRelFile(){
}
}
This gives me an error, even though I am overriding the constructor.
NOTE: This class is not finished. Don't make a comment about why wouldn't I need this or a comment about how this class is useless. I just started writing it before I got this Error.
Because you didn't make an explicit call to super(...) in your default constructor, it is implicitly attempting to call the default constructor for the super class, which, as you point out, doesn't exist in this case (the case of super being a File). The solution to your problem is to make a call to the super constructor in your default AbsRelFile() constructor. If you wan't to provide a default constructor for your class, you're going to need to call super(...) with some default values.
When you define a constructor, Java inserts an implicit call to the super constructor as the very first line of the constructor. So your constructor is equivalent to:
private AbsRelFile(){
super();
}
Since there is no default constructor in the super class File, it gives an error. To fix this, you need to place an explicit call to the super class constructor as the first line:
private AbsRelFile(){
super("fileName");
}
Most probably, you'll have to define some suitable parameters for AbsRelFile constructor too which you can pass to super call.
On another note, constructors cannot be overridden. So it is wrong to say that you're overriding the Object class constructor. You're simply defining a constrcutor for AbsRelFile class.
Constructors, by default, call the default constructor of the super-class if you don't make a super constructor call yourself.
To avoid this, make a call to an actually-defined constructor of File.
Java automatically puts in a call to super() in your empty constructor, which is why you get the error.
The problem is that your AbsRelFile constructor is trying to call the no-args constructor of File. What you have written is equivalent to
private AbsRelFile() {
super();
}
You need to make sure that you explicitly invoke one of the File constructors that does exist. For example:
private AbsRelFile() {
super("dummy");
}
Obviously, you will need to figure out a safe / harmless / appropriate superclass constructor and arguments to use for your particular use-case. (I haven't a clue what an AbsRefFile is really supposed to be ... so I cannot advise on that.)
Aside - you don't "override" constructors. Constructors are never inherited in Java, so overriding simply doesn't apply here. Instead you declare constructors in the subclass, and have them chain to the appropriate constructors in the immediate superclass via an explicit super(...) call ... or the implicit one the Java inserts by default.
First of all, I hope your field "File f" is not related to trying to access the superclass, but something to do with 'Rel' or 'Abs'..
The other posters have correctly pointed out that your implicit default constructor (AbsRelfile()) will attempt to call super() - which does not exist. So the only solution is to make a constructor that passes down some valid arguments.
If you are attempting to 'wrap' the whole java.util.File class (like when making your own Exception) you should probably provide a wrapper for each of the original constructors. Modern IDEs like Eclipse should have this a right-click away.
Note that File does not require that the given filename exists, in particular it does not exist when you want to do operations like file.mkdir().
If you need an actual, temporary file to work with, you could always do something like:
public class AbsRelFile() {
public AbsRelFile() {
super(File.createTempFile("AbsRelFile", "tmp").getAbsolutePath());
}
}
.. but I'm puzzled as to why you want to subclass File in the first place.
To explain WHY in one line:
When you define a constructor with a parameter (as in the File class), Java compiler WILL NOT generate the default constructor for you.

Categories

Resources