【发布时间】:2020-09-18 10:33:39
【问题描述】:
我有一个 Shape 方法,它有两个参数,第一个是宽度,第二个是高度。我有两个子类,一个是矩形,另一个是三角形。我想打电话给 area() 借助 Shape 类的 area() 在三角形和矩形中定义的方法。 我已经编写了这段代码,但是当我使用父类的 area() 方法调用派生类的 area() 方法时,出现错误。 那么如何做到这一点呢?
public class Shape {
double width, height;
public Shape(double w, double h)
{
this.height = h;
this.width = w;
}
public void area(Object shape){ // area method of parent class
shape.area(); // here I am getting error.
}
}
class triangle extends Shape{
triangle tri;
public triangle(double w, double h) {
super(w, h);
}
public void area()// area method of derived class
{
double area = (1/2)*width*height;
System.out.println("The area of triangle is: "+area);
}
}
class rectangle extends Shape{
rectangle rect;
public rectangle(double w, double h) {
super(w, h);
}
public void area() // area method of derived class
{
double area = width*height;
System.out.println("The area of rectangle is: "+area);
}
}
【问题讨论】:
-
您很可能正在寻找abstract methods and classes。 --- 备注:奇怪的是方法
area(...)期望Shape作为参数而不是使用this来计算并返回当前Shape的面积。 -
建议您以大写字母开头类名,以便人们更容易阅读您的代码。
-
@matt 不要这样做。如果必须重写一个方法,则该方法(以及周围的类)应声明为
abstract。 -
您应该阅读继承的基础知识。
-
请注意,(1/2) 将是 0。