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();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)