【发布时间】:2016-07-17 23:09:58
【问题描述】:
我正在尝试用 Java 实现一个程序,它有一个父类 RoundShapes 和两个子类 Sphere 和 Cone。当我尝试在我的子类中创建一个构造函数时,它给了我一个错误,即构造函数不能应用于该给定类型。 然后我研究并找到了一个关于继承的教程,他们使用了一个超级构造函数。我尝试使用它,但现在它给了我一个错误,即在超级构造函数之前不能使用半径?!我不在构造函数的范围内,所以我不确定那是什么意思。
import java.util.*;
public class Miller_A03Q4 {
public static void main(String[] args) {
Sphere sphere1 = new Sphere();
RoundShape cone1 = new RoundShape();
RoundShape.setRadius(4);
}
public static class RoundShape{
double area;
double volume;
double radius;
String shape;
//
public RoundShape(double r){
radius = r;
}
// set radius method
public void setRadius(double r){
radius = r;
}
// get area method
public double getArea(){
return area;
}
// get volume
public double getVolume(){
return volume;
}
}
// sphere is-a from roundshape
static class Sphere extends RoundShape{
public Sphere(double r){
radius = r;
}
//set area
public void setArea(){
area = 4 * Math.PI * radius * radius;
}
// get volume
public void setVolume(){
volume = (4/3) * Math.PI * radius * radius * radius;
}
}
//cone class is-a from roundshape
class Cone extends RoundShape{
double height;
//set area
public void setArea(){
area = Math.PI * radius * (radius + Math.sqrt( height * height + radius * radius));
}
// cone volume
public void setVolume(){
volume = Math.PI * radius * radius * (height/3);
}
}
}
【问题讨论】:
-
@AndrewL。它们被称为静态内部类,它们是一种语言特性。
-
@4castle 真的吗?我猜你每天都会学到一些新东西
标签: java inheritance constructor