Java 多态
多态是同一个行为具有多个不同表现形式或形态的能力。
多态就是同一个接口,使用不同的实例而执行不同操作,如图所示:
多态性是对象多种表现形式的体现。
现实中,比如我们按下 F1 键这个动作:
- 如果当前在 Flash 界面下弹出的就是 AS 3 的帮助文档;
- 如果当前在 Word 下弹出的就是 Word 帮助;
- 在 Windows 下弹出的就是 Windows 帮助和支持。
同一个事件发生在不同的对象上会产生不同的结果。
多态的优点
- 1. 消除类型之间的耦合关系
- 2. 可替换性
- 3. 可扩充性
- 4. 接口性
- 5. 灵活性
- 6. 简化性
多态存在的三个必要条件
- 继承
- 重写
- 父类引用指向子类对象
多态:
* 1.编译时多态:一个接口(方法),多种实现(方法的重载)
* 2.运行时多态:父类可以接收子类对象
*
* 多态的作用:屏蔽子类差异化,写出通用的代码
* 运行时多态的前提是建立在继承的基础之上!
public class Main {
public static class Bird {
public void fly() {
System.out.println("飞扬的小鸟");
}
}
public static class Chicken extends Bird{
public void fly() {
System.out.println("一只性感的小鸡");
}
}
public static class Duck extends Bird{
public void fly() {
System.out.println("用心做鸭");
}
}
public static class Goose extends Bird{
public void fly() {
System.out.println("红烧大鹅");
}
}
public static void main(String[] args) {
Bird bird = new Bird();
Chicken chicken = new Chicken();
Duck duck = new Duck();
Goose goose = new Goose();
//方式1:
bird.fly();
chicken.fly();
duck.fly();
goose.fly();
//方式2:
// 这里 体现了多态
//利用父类接收了不同的子类对象
Bird[] birds = {bird, chicken, duck, goose};
for(int i = 0; i < birds.length; i++) {
Bird b = birds[i];
b.fly();
}
}
}
运行结果:

//练习 /*小男孩遛狗 *Boy类: 遛狗 *黄狗类: 跑(占地盘) *黑狗类: 跑(打架) *白狗类:跑(撒娇) */
//package check;
public class Main {
public static class Boy {
public void playWithDog(Dog dog) {
dog.run();
}
}
public static class Dog {
public void run() {
System.out.println("奔跑在绿绿的大草原!");
}
}
public static class WhiteDog extends Dog{
public void run() {
System.out.println("小白小白你真可爱!");
}
}
public static class YellowDog extends Dog{
public void run() {
System.out.println("走大黄!我们去占地盘!嘿哈嘿哈");
}
}
public static class BlackDog extends Dog{
public void run() {
System.out.println("小黑!上啊!咬他!");
}
}
public static void main(String[] args) {
Boy boy = new Boy();
YellowDog yellowDog = new YellowDog();
BlackDog blackDog = new BlackDog();
WhiteDog whiteDog = new WhiteDog();
Dog[] dogs = {yellowDog, blackDog, whiteDog};
for (Dog dog : dogs) {
boy.playWithDog(dog);
}
}
}
运行结果 :

来源:CSDN
作者:辞树 LingTree
链接:https://blog.csdn.net/l18339702017/article/details/103837400