gpt4 book ai didi

java - Java中的数组继承

转载 作者:行者123 更新时间:2023-12-02 10:32:46 27 4
gpt4 key购买 nike

当我使用继承并定义父类的对象,然后从具有自己的属性的子类调用构造函数时,我遇到了问题。当我想使用 set 方法为子类分配值时,它给我一个错误(找不到符号)这是我的代码

    public class Shape {
private final double PI =3.14;
public Shape() {
}
public double getPI() {
return PI;
}
}

public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle() {
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
}
public class Circle extends Shape{
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}

}

public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Shape s[] = new Shape[3];
int type;
for (int i = 0; i < s.length; i++) {
System.out.println("Enter the Shape:\n 1.Rectangle \n 2.Circle");
type = in.nextInt();
if(type==1){
s[i] = new Rectangle();
s[i].setLength(5.5);
}
}
}

最佳答案

你的问题出在这里:

s[i] = new Rectangle();
s[i].setLength(5.5);

是的。您知道该表单是 Rectangle 的一个实例,JVM 只知道它是一个 Shape。如果您想将其用作矩形,则必须将其声明为一个:

Rectangle r = new Rectangle();
r.setLength(5.5);
s[i] = r;

编辑:这样做的原因是,当您将一个实例声明为 Shape (父类)时,JVM 会认为它是这样的,即使您的代码建议(对人类读者) )将使用特定类型,JVM 不会对将实例化哪个子类做出任何假设。您的可能性仅限于您声明的类别。

由于您现在再次将其保存为数组中的 Shape,如果稍后您想要获取该值,则需要对其进行转换。

Rectangle rNew = (Rectangle)s[index]; // of course after checking whether it is in fact a Rectangle

关于java - Java中的数组继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513700/

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