从孙 class 调用超级 class 构造函数,调用 parent 或 grandparent 构造函数?
Calling super class constructor from grandchild class, calls parent or grandparent constructor?
当使用来自 second-level child class 的超级 class 构造函数时,它会将参数传递给 grandparent 构造函数还是直接 parent 构造函数?
//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)?
}
super
调用直接父级的构造函数。因此 Third
中的 super
调用将调用 Second
的构造函数,后者又调用 First
的构造函数。如果您在构造函数中添加一些打印语句,这很容易自己看到:
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
Child 中的 super 试图从 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
*/
}
}
当使用来自 second-level child class 的超级 class 构造函数时,它会将参数传递给 grandparent 构造函数还是直接 parent 构造函数?
//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)?
}
super
调用直接父级的构造函数。因此 Third
中的 super
调用将调用 Second
的构造函数,后者又调用 First
的构造函数。如果您在构造函数中添加一些打印语句,这很容易自己看到:
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
Child 中的 super 试图从 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
*/
}
}