Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling superclass constructor with super or just setTitle?

Tags:

java

jframe

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

like image 356
Johan Lindskogen Avatar asked Oct 17 '12 15:10

Johan Lindskogen


People also ask

How do you call a superclass constructor?

To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

Does Java call super constructor automatically?

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

What happens if super () is not coded?

If we call "super()" without any superclass Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).

Is Super mandatory in constructor?

In that case it is necessary to put super(...) and specify the constructor. So it is possible there is not an accessible no arg constructor in which case super is necessary and must have arguments for an accessible constructor.


2 Answers

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").

like image 138
Keppil Avatar answered Oct 08 '22 17:10

Keppil


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.

like image 31
Joeri Hendrickx Avatar answered Oct 08 '22 17:10

Joeri Hendrickx