我做了一个类,然后从它的两个子类。图超类有一个名为are()的方法。这是全班同学。android覆盖子类中的函数
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;
}
}
易打印outpute我做
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 但前来0 0 0
父类的方法名应该与子类中的overriden相同。看[this](https://www.javatpoint.com/method-overriding-in-java)。如果没有正确学习概念,不要发布问题。 –