什么在这里调用 super class 构造函数?
What is invoking the super class constructor here?
我在寻找备考题时偶然发现了这段代码。
我不明白什么在调用超类构造函数
在这段代码中?
输出是 ---> 猫美洲狮 cc
THL
public class Feline{
public String type = "f ";
public Feline(){
System.out.print("feline ");
}
}
-
public class Cougar extends Feline {
public Cougar(){
System.out.print("cougar ");
}
public static void main(String[] args){
new Cougar().go();
}
void go(){
type = "c ";
System.out.print(this.type + super.type);
}
}
如果您不包含对父构造函数的调用,那么将在当前 class
的第一行执行之前调用父构造函数(无参数)
在这种情况下,Java 编译器将自动插入对 super()
的调用。我建议阅读 this Java tutorial,特别是这部分:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
当你有一个 class 扩展其他 class,例如 Cougar extends Feline
,必须 调用超级 class 在构造函数的顶部。当你不写一个时,Java 假定你打算调用默认的超级 class 构造函数。所以你的构造函数:
public Cougar(){
System.out.print("cougar ");
}
实际解释为:
public Cougar(){
super();
System.out.print("cougar ");
}
因此调用了超级 class 构造函数。有趣的是,因为所有 class 都是 class Object
的扩展,所以在每个构造函数的开头都会调用超级 class 构造函数我会写 - 要么是你已经包含的带参数或不带参数的显式,要么是默认的 super class 构造函数,如果你没有指定的话。
我在寻找备考题时偶然发现了这段代码。 我不明白什么在调用超类构造函数 在这段代码中?
输出是 ---> 猫美洲狮 cc
THL
public class Feline{
public String type = "f ";
public Feline(){
System.out.print("feline ");
}
}
-
public class Cougar extends Feline {
public Cougar(){
System.out.print("cougar ");
}
public static void main(String[] args){
new Cougar().go();
}
void go(){
type = "c ";
System.out.print(this.type + super.type);
}
}
如果您不包含对父构造函数的调用,那么将在当前 class
的第一行执行之前调用父构造函数(无参数)在这种情况下,Java 编译器将自动插入对 super()
的调用。我建议阅读 this Java tutorial,特别是这部分:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
当你有一个 class 扩展其他 class,例如 Cougar extends Feline
,必须 调用超级 class 在构造函数的顶部。当你不写一个时,Java 假定你打算调用默认的超级 class 构造函数。所以你的构造函数:
public Cougar(){
System.out.print("cougar ");
}
实际解释为:
public Cougar(){
super();
System.out.print("cougar ");
}
因此调用了超级 class 构造函数。有趣的是,因为所有 class 都是 class Object
的扩展,所以在每个构造函数的开头都会调用超级 class 构造函数我会写 - 要么是你已经包含的带参数或不带参数的显式,要么是默认的 super class 构造函数,如果你没有指定的话。