gpt4 book ai didi

java - Java 中的“Super”关键字

转载 作者:行者123 更新时间:2023-12-01 18:25:36 24 4
gpt4 key购买 nike

我有一个关于 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 如何知道在子类中调用哪个构造函数?因为在我的父类(super class)中,我有两个没有参数的构造函数;public double getRadius() 和 public double getArea()

最佳答案

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

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){
//....
}

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

关于java - Java 中的“Super”关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com