多态

来源:互联网 发布:雅诗兰黛眼霜 知乎 编辑:程序博客网 时间:2024/06/17 20:26

1、概念

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

(2)三个必要条件:继承(或实现)、重写(或重载)、向上转型

(3)向上转型

Father f = new Son();//父类引用指向子类实例

(4)向下转型

Son s = (Son)new Father();//父类对象强制转换为子类对象

2、代码示例

求下面程序输出结果:

public class A {    public String show(D obj) {        return ("A and D");    }    public String show(A obj) {        return ("A and A");    } }public class B extends A{    public String show(B obj){        return ("B and B");    }    public String show(A obj){        return ("B and A");    } }public class C extends B{}public class D extends B{}public class Test {    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("1--" + a1.show(b));        System.out.println("2--" + a1.show(c));        System.out.println("3--" + a1.show(d));        System.out.println("4--" + a2.show(b));        System.out.println("5--" + a2.show(c));        System.out.println("6--" + a2.show(d));        System.out.println("7--" + b.show(b));        System.out.println("8--" + b.show(c));        System.out.println("9--" + b.show(d));          }}

代码输出:

1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D

(1)向上转型之后,父类引用只能调用父类中的成员,若父类中的成员在子类中重写,则只能调用子类的成员,“子类优先”。

(2)子类对象的引用,能调用子类中的所有成员,以及父类中的非私有成员,若重写了父类中的成员,则只能调用子类的成员,“子类优先”。