Java 中的“Super”关键字

问题描述 投票:0回答:3

我有一个关于 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;
}
}

我的观点是,当我在子类中使用 super() 时,java 如何知道在子类中调用哪个构造函数?因为在我的超类中,我有两个没有参数的构造函数; 公共双 getRadius() 和公共双 getArea()

java super
3个回答
5
投票

您的超类中只有一个构造函数,即默认的无参数构造函数,该构造函数未在类中显式定义。每个子类的构造函数都会调用超类中的这个构造函数。

getRadius()
getArea()
只是
super
类中的方法,它们不是构造函数。请记住,构造函数始终采用以下形式:

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

因此

Circle
类的构造函数如下所示:

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

}

如果

super
类中有多个构造函数,那么我们说:

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

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

编译器将使用参数来确定要调用哪个构造函数。


0
投票

构造函数名称将是类名称。你正在谈论那里的方法。

class classname{

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

}

0
投票
 public void setRadius(double radius){
    this.radius = 1; 

}
public double getRadius(){
    return this.radius;
}
public void setArea(double radius){
    this.area = area;
}

您编写的所有这些方法都不是构造函数。 构造函数的名称始终与类的名称相同。 因此,编译器使用内置构造函数,它将为您的变量分配默认值。 在您的情况下,半径和面积均为 0.0。

请阅读本文以获取进一步说明:https://www.w3schools.com/java/java_constructors.asp

© www.soinside.com 2019 - 2024. All rights reserved.