java多态(上传)

package ant;

class Figure {
    int getArea(int w,int h) {
        return w+h;
    }
}

class Rectangle extends Figure {
    int getArea(int w,int h) {
        return w*h;
    }    //求矩形面积方法
}

class Triangle extends Figure {
    int getArea(int w,int h) {
        return (w*h)/2;
    }    //求三角形面积方法
}

class Area {
    public static void main(String[] args) {
        Figure f0;
        Figure f1;
        f0 = new Rectangle();           
        f1 = new Triangle();
        System.out.println(f0.getArea(4,5));
        System.out.println(f1.getArea(4,5));
    }
}

输出结果

20

10

这里需注意的是f0,f1均是调用子类的方法getArea(in w,int h);但若父类中没有getArea(int w,int h)方法,编译会报错

posted on 2013-03-14 16:00  cursem  阅读(83)  评论(0)    收藏  举报