在Java中,构造函数负责特定类的对象创建。除构造函数的其他功能外,它还实例化其类的属性/实例。在Java中,默认情况下,super()
方法用作每个类的构造函数的第一行,此处此方法的目的是调用其父类的构造函数,以便在子类继承并使用它们之前很好地实例化其父类的属性。
这里要记住的一点是创建对象时会调用构造函数,但并非必须要在每次调用类的构造函数时都创建该类的对象。在上述情况下,从构造函数中调用parent的construcotr子类的子类,但仅创建子类的对象,因为子类与它的父类处于is-关系。
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 complier call parent class constructor //by adding super() method at 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. } }
输出结果
parent class constructor called.. InheritanceObjectCreation subclass constructor called.. InheritanceObjectCreation