Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call super() in a constructor?

I'm dealing with a class which extends JFrame.

It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();

like image 246
mark Avatar asked May 08 '12 23:05

mark


People also ask

Is it necessary to call super () inside a constructor?

However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.

Where super () can be used within a constructor?

super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor.


1 Answers

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame {     public MyFrame() {         super("My Window Title");         ...     } } 
like image 106
AerandiR Avatar answered Oct 07 '22 17:10

AerandiR