多态

 1.多态概述

        多态就是使用父类类型的变量引用子类对象,根据被引用子类对象的特性,程序会得到不同的运行效果。

     

       

                

       

二、重载、重写、多态经典实例

package object;

class A {
public String show(D obj) {
return ("A and D");
}

public String show(A obj) {
return ("A and A");
}
}

class B extends A {
public String show(B obj) {
return ("B and B");
}

public String show(A obj) {
return ("B and A");
}

}

class C extends B {
}

class D extends B {
}

public class myTest {


public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();

System.out.println("⑴ " + a1.show(b));
System.out.println("⑵ " + a1.show(c)); 
System.out.println("⑶ " + a1.show(d));
System.out.println("⑷ " + a2.show(b)); 
System.out.println("⑸ " + a2.show(c));
System.out.println("⑹ " + a2.show(d)); 
System.out.println("⑺ " + b.show(b)); 
System.out.println("⑻ " + b.show(c)); 
System.out.println("⑼ " + b.show(d)); 
}

}

输出结果 :

⑴ A and A
⑵ A and A
⑶ A and D
⑷ B and A
⑸ B and A
⑹ A and D
⑺ B and B
⑻ B and B
⑼ A and D

详解:
a1.show(b));Class A 中没有show(B obj),B转向B的父类A,执行A show(A obj)--->return "A and A" ——Java向上转型

a1.show(c));Class A 中没有show(C obj),C转向C的父类B,Class A 中没有show(B obj),再转向父类A,执行A show(A obj)--->return "A and A"

a1.show(d));Class A 中有show(D obj)执行A show(D obj)--->return "A and D"

这个比较特殊:A a2 = new B();父类声明,子类实例,你应该把a2当作子类重写完后的父类看,注意只有父类的方法

a2.show(b));Class A 中没有show(B obj),B转向B的父类A,执行A show(A obj),A的show 方法被重写,执行B show(A obj)--->return "B and A"

a2.show(c));Class A 中没有show(C obj),C转向C的父类B,Class A 中没有show(B obj),B转向父类A,执行A show(A obj),A的show 方法被重写,执行B show(A obj)--->return "B and A"

a2.show(d));Class A 中有show(D obj)执行A show(D obj)--->return "A and D"
b.show(b)); Class B 中有show(B obj)--->return "B and B"

b.show(c)); Class B 中没有show(C obj),C转向C的父类B,执行B show(B obj)--->return "B and B"

b.show(d)); Class B 中有继承了Class A 的show(D obj),执行A show(D obj)--->return "A and D"

三、转型

面向对象中的转型只会发生在有继承关系的子类和父类中(接口的实现也包括在这里)。
加入有父类:人,子类:男人和女人。
向上转型: Person p = new Man() ; //向上转型不需要强制类型转化
向下转型之前一定要先做向上转型,正确的做法是: Person p = new Man(); //先将Man的实例向上转型成Person的实例(向上转型)
                        Man man = (Man)p; //将被转型来的p实例进行强制转换成Man的实例man(向下转型

只有非静态的成员方法,编译看左边(父类),运行看右边 (子类)。
多态的弊端,就是:不能使用子类特有的成员属性和子类特有的成员方法。
实例参考<em>JAVA</em>的<em>多态</em>用几句话能直观的解释一下吗? - 程序狗的回答 - 知乎 https://www.zhihu.com/question/30082151/answer/120520568 用几句话能直观的解释一下多态吗?



em  [em]  详细X
基本翻译
n. 西文排版行长单位
adj. 全身长的
abbr. 地球质量(earth mass);放射(emanation);电子邮件(email)
pron. 他们(等于them)
n. (Em)人名;(德、挪、罗、土)埃姆;(柬)恩
网络释义
Em: М
尼康 EM: Nikon EM
原文地址:https://www.cnblogs.com/thiaoqueen/p/6516293.html