介绍
多态是同一个行为具有多个不同表现形式或形态的能力。
多态就是同一个接口,使用不同的实例而执行不同操作,如图所示:

多态性是对象多种表现形式的体现。
现实中,比如我们按下 F1 键这个动作:
如果当前在 Flash 界面下弹出的就是 AS 3 的帮助文档;如果当前在 Word 下弹出的就是 Word 帮助;在 Windows 下弹出的就是 Windows 帮助和支持。同一个事件发生在不同的对象上会产生不同的结果。
立即学习“Java免费学习笔记(深入)”;
多态的优点小褚类型之间的耦合性可替代性可扩充性接口性灵活性简化性多态存在的三个必要条件继承重写父类引用指向子类对象:Parent p = new Child();

向上转型、隐式转型、自动转型:子类对象转型为父类对象,可以调用子类重写父类的方法以及父类派生的方法,无法调用子类独有的方法
向上转型的语法:
父类类型 父类引用 = new 子类类型(参数);
<pre class="brush:php;toolbar:false;">public class Test { public static void main(String[] args){ Animal one=new Animal();//1 Animal two=new Cat();//2 Animal three=new Dog();//3 one.eat(); two.eat(); three.eat(); }}向下转型、强制类型转换:子类引用指向父类对象,此处必须进行强制类型转换
必须满足转型条件,才能转换
代码语言:javascript代码运行次数:0运行复制<pre class="brush:php;toolbar:false;">public class Test { public static void main(String[] args){ Cat temp=(Cat) two; temp.eat(); temp.run(); temp.getWeight(); }}它的作用是测试它左边的对象是否是它右边的类的实例

<pre class="brush:php;toolbar:false;">public class Test { public static void main(String[] args){ if (two instanceof Cat) { Cat temp = (Cat) two; temp.eat(); temp.run(); temp.getWeight(); System.out.println("two可以转换为Cat类型"); } if (two instanceof Dog) { Dog temp2 = (Dog) two; temp2.eat(); temp2.sleep(); temp2.getSex(); System.out.println("two不能转换为Dog类型"); } if(two instanceof Animal){ System.out.println("Animal"); } if (two instanceof Object){ System.out.println("Object"); } }}<pre class="brush:php;toolbar:false;">public class Master { //方案一:编写方法传入不同类型的动物,调用各自的方法 public void feed(Cat cat){ cat.eat(); cat.playxq(); } public void feed(Dog dog){ dog.eat(); dog.sleep(); } //方案二:编写方法传入动物的父类,方法中通过类型转换,调用指定子类的方法 public void feed(Animal obj){ if (obj instanceof Cat) { Cat one = (Cat) obj; one.eat(); one.playxq(); }else if (obj instanceof Dog){ Dog two=(Dog) obj; two.eat(); two.sleep(); } }}在面向对象的概念中,所有的对象都是通过类来描绘的,但是反过来,并不是所有的类都是用来描绘对象的,如果一个类中没有包含足够的信息来描绘一个具体的对象,这样的类就是抽象类。
抽象类除了不能实例化对象之外,类的其它功能依然存在,成员变量、成员方法和构造方法的访问方式和普通类一样。
由于抽象类不能实例化对象,所以抽象类必须被继承,才能被使用。也是因为这个原因,通常在设计阶段决定要不要设计抽象类。
abstract
<pre class="brush:php;toolbar:false;">public abstract class Animal{}经过
abstract
<pre class="brush:php;toolbar:false;">public abstract void eat();
包含抽象方法的类一定是抽象类
static
final
private
abstarct
以上就是Java多态(上)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号