我做了一個類,然後從它的兩個子類。圖超類有一個名爲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)。如果沒有正確學習概念,不要發佈問題。 –