当使用来自二级子类的超类构造函数时,它是否将参数传递给祖父项构造函数或直接父构造函数?
//top class
public First(type first){
varFirst = first;
}
//child of First
public Second(type second){
super(second); //calls First(second)
}
//child of Second
public Third(type third){
super(third); //calls First(third) or Second(third)?
}
答案 0 :(得分:6)
super
调用直接父级的构造函数。因此,super
中的Third
电话会调用Second
的构造函数,而构造函数又调用First
。如果在构造函数中添加一些print语句,这很容易看到:
public class First {
public First(String first) {
System.out.println("in first");
}
}
public class Second extends First {
public Second(String second) {
super(second);
System.out.println("in second");
}
}
public class Third extends Second {
public Third(String third) {
super(third);
System.out.println("in third");
}
public static void main(String[] args) {
new Third("yay!");
}
}
您获得的输出:
in first
in second
in third
答案 1 :(得分:0)
super in Child尝试从Parent获取信息,而Parent中的super尝试从GrandParent获取信息。
public class Grandpapa {
public void display() {
System.out.println(" Grandpapa");
}
static class Parent extends Grandpapa{
public void display() {
super.display();
System.out.println("parent");
}
}
static class Child extends Parent{
public void display() {
// super.super.display();// this will create error in Java
super.display();
System.out.println("child");
}
}
public static void main(String[] args) {
Child cc = new Child();
cc.display();
/*
* the output :
Grandpapa
parent
child
*/
}
}