使用Println显示超类方法的结果

时间:2014-12-21 15:57:08

标签: java

我开发了这三个类: -

一个findArea

package myapp;

public class FindArea {

    public static void main(String[] args) {
        Figure f = new Figure(10, 10);
        Rectangle r = new Rectangle(4, 4);
        Triangle t = new Triangle(4,8);
        Figure figref;
        figref = r;
        System.out.println("Area is: " + r.area());
        System.out.println(figref.area());

        System.out.println(t.area());
        System.out.println("Area is: " + f.area());
    }
}

矩形

package myapp;

public class Rectangle extends Figure {
    Rectangle(double a, double b) {
        super(a, b);
    }

    double area() {
        System.out.println("Area of Rectangle is:");
        return width*length;
    }
}

三角

package myapp;

public class Triangle extends Figure {
    Triangle(double a, double b) {
        super(a,b);
    }

    double area() {
        System.out.println("Area of Triangle is: ");
        return (width/2)*length;
    }

}

package myapp;

public class Figure {
    double width;
    double length;

    Figure(double dimL, double dimW) {
        width = dimW;
        length = dimL;
    }

    double area () {
        System.out.println("Unknown shape. Area cannot be defined.");
        return 0;
    }
}

我希望 FindArea 的输出显示以下内容: -

Area is: Area of Rectangle is:
16.0
Area of Rectangle is:
16.0
Area of Triangle is: 
16.0
Unknown shape. Area cannot be defined.
Area is: 0.0

相反,显示的结果如下:

Area of Rectangle is:
16.0
Area of Triangle is: 
16.0
Unknown shape. Area cannot be defined.
Area is: 0.0

为什么忽略了System.out.println("Area is: " + r.area());行?

1 个答案:

答案 0 :(得分:1)

System.out.println("Area is: " + r.area());语句不会被忽略。实际上,程序的输出如下所示:

Area of Rectangle is:
Area is: 16.0
Area of Rectangle is:
16.0
Area of Triangle is: 
16.0
Unknown shape. Area cannot be defined.
Area is: 0.0

因此,您可以看到正确打印Area is:

声明System.out.println("Area is: " + r.area());执行以下操作:

    首先调用
  1. r.area()
  2. 由于语句Area of Rectangle is:
  3. ,这会导致System.out.println("Area of Rectangle is:")首先显示
  4. 返回返回值width * length,在本例中为16.0。这是由第一个println打印的,如下所示:Area is: 16.0