子类和父类的构造方法关系

发布时间 2023-10-28 21:21:41作者: xiaoovo

在Java中,子类在初始化时会自动调用父类的无参构造方法。如果父类没有无参构造方法,子类必须显式地调用父类的构造方法,或者提供一个包含调用父类构造方法的构造方法。

当子类的构造方法被调用时,JVM会在初始化子类的过程中自动调用父类的构造方法。这个过程是自动的,不需要显式地在子类构造方法中调用父类的构造方法。

但是,如果父类有多个构造方法,子类不会自动调用父类的所有构造方法,只会默认调用父类的无参数构造方法。如果需要在子类中调用父类的其他构造方法,需要在子类的构造方法中使用super()来显式地调用所需的父类构造方法。

public class Parent {
    public Parent() {
        System.out.println("Parent class's parameterless method called");
    }
}
public class Son extends Parent{
    public Son() {
        System.out.println("Son class's parameterless method called");
    }
    public Son(int i) {
        System.out.println("Son class's parameter method called");
    }

    public static void main(String[] args) {
        Son son1 = new Son();
        Son son2 = new Son(1);
    }
}
Parent class's parameterless method called
Son class's parameterless method called
Parent class's parameterless method called
Son class's parameter method called

Process finished with exit code 0