English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Java, the constructor is responsible for creating objects of a specific class. In addition to other functions of the constructor, it also instantiates the properties of its class/instance. By default, in Java,super()
The method is used as the first line of the constructor for each class. The purpose of this method is to call the constructor of its superclass, so that the properties of the superclass are well instantiated before the subclass inherits and uses them.
One thing to remember is that when creating objects, constructors are called, but it is not necessary to create an object of the class every time the constructor of the class is called. In the above case, the parent's constructor of the subclass is called from the constructor, but only the object of the subclass is created, because the subclass and its parent class are in the is-relationship.
class InheritanceObjectCreationParent { public InheritanceObjectCreationParent() { System.out.println("parent class constructor called..."); System.out.println(this.getClass().getName()); //to know the class of which object is created. } } public class InheritanceObjectCreation extends InheritanceObjectCreationParent { public InheritanceObjectCreation() { //here we do not explicitly call super() method but at runtime compiler call parent class constructor //by adding super() method at the first line of this constructor. System.out.println("subclass constructor called..."); System.out.println(this.getClass().getName()); //to know the class of which object is created. } public static void main(String[] args) { InheritanceObjectCreation obj = new InheritanceObjectCreation(); // object creation. } }
Output Result
parent class constructor called... InheritanceObjectCreation subclass constructor called... InheritanceObjectCreation