开发者社区> 问答> 正文

Java 方法覆盖(Overriding)代码的实现

Java 方法覆盖(Overriding)代码的实现

展开
收起
珍宝珠 2020-02-12 19:55:46 1568 0
1 条回答
写回答
取消 提交回答
  • public class Findareas{
        public static void main (String []agrs){
            Figure f= new Figure(10 , 10);
            Rectangle r= new Rectangle(9 , 5);
            Figure figref;
            figref=f;
            System.out.println("Area is :"+figref.area());
            figref=r;
            System.out.println("Area is :"+figref.area());
        }
    }
    class Figure{
        double dim1;
        double dim2;
        Figure(double a , double b) {
            dim1=a;
            dim2=b;
        }
        Double area() {
            System.out.println("Inside area for figure.");
            return(dim1*dim2);
        }
    }
    class Rectangle extends Figure {
        Rectangle(double a, double b) {
            super(a ,b);
        }
        Double area() {
            System.out.println("Inside area for rectangle.");
            return(dim1*dim2);
        }
    }
    
    

    以上代码运行输出结果为:

    Inside area for figure.
    Area is :100.0
    Inside area for rectangle.
    Area is :45.0
    
    2020-02-12 19:56:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载