显性隐性调用父类的构造方法

来源:百度知道 编辑:UC知道 时间:2024/06/25 02:55:53
在JAVA中怎么算做显性、隐性调用父类的构造方法呢?

谁能给出个概念,最好给段简便点的注释代码。。。谢谢!

都没说出核心:
所谓显示,就是要你自己写调用代码(即new),
所谓隐式,就是你不写调用,编译器在编译你的代码时,会自动帮你加上调用父类的构造函数方法。
class Parent {
private int i = 0;

public Parent(){
System.out.println("Parent()被调用了");
}
}

class Son extends Parent{
public Son(){
super();//这句话可写可不写,如果不写,编译器在编译为字节码时,会自动帮你加上这句话,就是所谓的隐式调用啦。
System.out.println("Son()被调用了"); }
}

public class Test{
public static void main(String[] args){
Son obj1 = new Son(); //仅调用自身构造函数,为显示调用
Parent obj2 = new Son(); //先调用父类的构造函数,在调用子类的构造函数,调用父类的构造函数为隐式调用
}
}

显性就是NEW 父类,隐性就是NEW 子类。因为NEW子类的时候也调用了父类的构造方法!

public class Person{
public Person(){
System.out.println("这是父类的构造方法");
}
}
public class student extends Person{
public student(){
System.out.println("这是子类的构造方法");
}
}

然后你在一个测试类里调用 new student()
控制台就会显示