简体   繁体   English

Java中的“超级”关键字

[英]'Super' keyword in Java

I have an issue regarding the super keyword in java. 我在java中有关于super关键字的问题。 Follow the example below: 请遵循以下示例:

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;
}
}

My point is that, when I use super() in the subclass, how java will know which constructor to call in my subclass ? 我的观点是,当我在子类中使用super()时,java如何知道子类中要调用哪个构造函数? Since in my superclass, I have two constructors with no arguments; 因为在我的超类中,所以我有两个没有参数的构造函数。 public double getRadius() and public double getArea() public double getRadius()和public double getArea()

There is only one constructor in your super class, the default no argument constructor which is not explicitly defined within the class. 在您的超类中只有一个构造函数,默认的无参数构造函数没有在该类中明确定义。 Each of the subclass's constructors will invoke this constructor in the super class. 子类的每个构造函数都将在超类中调用此构造函数。

getRadius() and getArea() are just methods within the super class, they are not constructors. getRadius()getArea()只是super类中的方法,它们不是构造函数。 Remember that constructors always take the form of: 请记住,构造函数始终采用以下形式:

[access modifier] [Class Name](/* arguments optional*/){}

So a constructor for the Circle class would look like: 因此, Circle类的构造函数如下所示:

public Circle(/*Arguments could go here */){

}

If there were more than one constructor in the super class, let's say: 如果super类中有多个构造函数,则说:

public Circle(int radius){
  //....
}

public Circle(double radius){
  //....
}

The compiler would use the arguments to determine which constructor to call. 编译器将使用参数确定要调用的构造函数。

Constructor name will be the class name. 构造函数名称将为类名称。 You are talking about the methods there. 您正在谈论那里的方法。

class classname{

   classname(){// constructor name as class name.
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM