2017-07-27 71 views
-2

我做了一个类,然后从它的两个子类。图超类有一个名为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

+1

父类的方法名应该与子类中的overriden相同。看[this](https://www.javatpoint.com/method-overriding-in-java)。如果没有正确学习概念,不要发布问题。 –

回答

0

的父类有一个方法叫做

double are() 

子类

double area() 

,所以它没有覆盖

0

你在这两个RectangleTriangle要重写的功能被称为area AND NOT are如Figure类

0

你是调用超类图的are()函数,而不是area()函数的子类。