我有一个关于 java 中 super 关键字的问题。请按照下面的示例操作:
public class Circle {
private double radius;
private double area;
public void setRadius(double radius){
this.radius = 1;
}
public double getRadius(){
return this.radius;
}
public void setArea(double radius){
this.area = area;
}
public double getArea(){
return this.area = Math.PI * radius * radius;
}
}
public class Cylinder extends Circle {
private double height;
public Cylinder(){
super();
height = 1;
}
public Cylinder(double height){
super();
this.height = height;
}
public Cylinder(double radius, double height){
super();
this.height = height;
public double getHeight(){
return height;
}
}
public double getVolume(){
return getArea()*height;
}
}
Run Code Online (Sandbox Code Playgroud)
我的观点是,当我在子类中使用 super() 时,java 如何知道在子类中调用哪个构造函数?因为在我的超类中,我有两个没有参数的构造函数;公共双 getRadius() 和公共双 getArea()
超类中只有一个构造函数,即默认的无参数构造函数,该构造函数未在类中显式定义。每个子类的构造函数都会调用超类中的这个构造函数。
getRadius()和getArea()只是super类中的方法,它们不是构造函数。请记住,构造函数始终采用以下形式:
[access modifier] [Class Name](/* arguments optional*/){}
Run Code Online (Sandbox Code Playgroud)
因此该类的构造函数Circle如下所示:
public Circle(/*Arguments could go here */){
}
Run Code Online (Sandbox Code Playgroud)
如果类中有多个构造函数super,假设:
public Circle(int radius){
//....
}
public Circle(double radius){
//....
}
Run Code Online (Sandbox Code Playgroud)
编译器将使用参数来确定要调用哪个构造函数。