gpt4 book ai didi

Java覆盖问题

转载 作者:行者123 更新时间:2023-12-03 20:37:17 25 4
gpt4 key购买 nike

我有类 Rectangle 继承的类 Shape,如下所示:

//Class Shape
public class Shape {
public double area(){
return 0.0;
}
}

//Class Rectangle
public class Rectangle extends Shape{

private int width;
private int height;
public Rectangle(int width,int height){
this.width=width;
this.height=height;
}

public void helloRectange(){
System.out.println("Hello Rectangle");
}


public double area(){
return this.height*this.width;
}

}

//And Test Class


public class TestShape {

public static void main(String []arge){

Shape shape2=new Rectangle(10,20);

shape2.helloRectange();


System.out.println("Rectange is"+shape2.area());
}

}

我无法使用 shape2 对象调用 shape2.helloRectange(); 方法?谁能详细解释一下。

错误是:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method helloRectange() is undefined for the type Shape at com.test.overriding.concept.TestShape.main(TestShape.java:9)

最佳答案

因为 Shape 类没有方法 helloRectange ,更改:

形状 shape2=new Rectangle(10,20);

到:

矩形 shape2=new Rectangle(10,20);

或像这样转换对象:

((Rectangle)shape2).helloRectange();

关于Java覆盖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567891/

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