Java編程基礎篇之多態性

通過繼承和重載的結合,超類可以定義供他所有子類可以使用方法的通用形式。如下代碼:

class Figure
{  
    double dim1;
    double dim2;
    
    Figure(double a, double b)
    {
        dim1 = a;
        dim2 = b;
    }
    
    double GetArea()
    {
        System.out.println("The figure is undefined!");
        return 0;
    }
}

class Rectangle extends Figure
{
    Rectangle(double a, double b)
    {
        super(a, b);
    }
    
    double GetArea()
    {
        System.out.println("this is in Rectangle.");
        return dim1 * dim2;
    }
}

class Triangle extends Figure
{
    Triangle(double a, double b)
    {
        super(a, b);
    }
    
    double GetArea()
    {
        System.out.println("this is in Triangle.");
        return dim1 * dim2/2;
    }
}

public class HelloWorld
{

    public static void main(String[] args)
    {
        Figure      f = new Figure(1, 2);
        Rectangle   r = new Rectangle(3, 4);
        Triangle    t = new Triangle(5, 6);
        
        Figure      area;
        
        area = f;
        System.out.println("area = " + area.GetArea());
        area = r;
        System.out.println("area = " + area.GetArea());
        area = t;
        System.out.println("area = " + area.GetArea());
    }
}

運行結果:

The figure is undefined!
area = 0.0
this is in Rectangle.
area = 12.0
this is in Triangle.
area = 15.0


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章