java 安卓重写子类中的函数
我创建了一个类图,然后从中创建了两个子类。Figure super类有一个名为are()的方法。这是全班的
public class Figure
{
public double a, b;
public Figure(double a,double b) {
this.a = a;
this.b = b;
}
public double are() {
return 0;
}
}
public class Rectangle extends Figure
{
Rectangle(double a, double b) {
super(a,b);
}
double area (){
return this.a*this.b;
}
}
class Triangle extends Figure
{
Triangle(double a, double b) {
super(a,b);
}
// override area for right triangle
double area () {
return a * b / 2;
}
}
为了便于打印输出,我制作了
public void toastM(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
现在我使用这个代码
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
toastM("are..... " + figref.are());
figref = t;
toastM("are..... " + figref.are());
figref = f;
toastM("are..... " + figref.are());
预期值为45 40 0 但是它来了
# 1 楼答案
父类有一个名为
儿童班
所以它没有被覆盖
# 2 楼答案
在
Rectangle
和Triangle
中重写的函数称为area
,而不是像Figure类中那样are
# 3 楼答案
调用的是超类Figure的are()函数,而不是子类的area()函数