java中关于多态的理解

多态:是同一个行为具有多个不同表现形式或形态的能力。

在代码的运用中主要是关于子类中方法的重写,实现了同一个父类接口可以进行不同子类中重写的方法

复制代码
public class GeometricOject {//父类

    public double findArea(){
        return 0.0;
    }
}
class Circle extends GeometricOject{//子类
    private double radius;
    public Circle(double radius){
        this.radius=radius;
    }
    @Override
    public double findArea() {
        return Math.PI*radius*radius;
    }
}
class MyRectangle extends GeometricOject{//子类
        private double height;
        private double width;
    public MyRectangle(double height,double width){
        this.width=width;
        this.height=height;
    }
    @Override
    public double findArea() {
        return height*width;
    }
}
复制代码
复制代码
public class GeometricTest {
    public static void main(String[] args) {
        GeometricTest test=new GeometricTest();
        Circle c=new Circle(5);
        MyRectangle m=new MyRectangle(3,5);
        test.displayGeoetricTest(c);
        test.displayGeoetricTest(m);

    }
    public void displayGeoetricTest(GeometricOject g){//相当于GeometricOject g=new Circle();
        System.out.println(g.findArea());
    }
}
复制代码

 

在GeometricTest中,我们声明了displayGeoetricTest方法,我们的接口是父类类型,但是我们传给他的却是子类Circle和子类MyRectangle类型,在编译器中认为是调用父类的findArea,但在实际代码运行中调用的是子类中findArea方法,从而实现多态——一个接口调用了不同子类中重写的方法,也可写作GeometricOject g=new Circle();但是多态也有局限性,不能使用此方法调用子类中特有的方法

多态的使用有以下三个要求:

  • 继承
  • 重写
  • 父类引用指向子类对象:Parent p = new Child();
posted @   justlearn  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示