多态

来源:互联网 发布:剑三正太捏脸数据 南风 编辑:程序博客网 时间:2024/06/05 00:19

1、概念

多态:一个接口,多种实现,也就是同一种事物表现出的多种形态。

接口是对事物的抽象,但是具体的实例的在处理相同消息的时候方式会不一样。

例如:开的动作,有些人开窗,有些人开门。

多态允许父类引用指向子类对象,调用的方法也是子类的方法

2、作用

应用程序不必为每一个派生类编写功能调用,只需要对抽象基类进行处理即可。提高了复用性

派生类的功能可以被基类调用,可以提高可扩充性和可维护性


3应用:

3.1、隐式类型转换

public class PolyTest{    public static void main(String[] args)    {                //向上类型转换,只需隐式转换        Animal animal = new Cat();        animal.sing();
<pre name="code" class="java"><span style="white-space:pre"></span>//编译错误        //用父类引用调用父类不存在的方法        //Animal a1 = new Cat();        //a1.eat();
//向下类型转换,需要显示转换 Animal a = new Cat(); Cat c = (Cat)a; c.sing(); c.eat(); //编译错误 /向下类型转换时只能转向指向的对象类型 //Animal a2 = new Cat(); //Dog c2 = (Dog)a2; }}class Animal{ public void sing() { System.out.println("Animal is singing!"); }}class Dog extends Animal{ public void sing() { System.out.println("Dog is singing!"); }}class Cat extends Animal{ public void sing() { System.out.println("Cat is singing!"); } public void eat() { System.out.println("Cat is eating!"); }}
3.2
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...{}  

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));   ①  //A and A    A.show(B)-->super.show(B)-->A.show(super(B))-->AA        System.out.println(a1.show(c));   ②  //A and A    A.show(C)-->super.show(C)-->A.show(super(C)-->A.show(super(super(C)))-->AA        System.out.println(a1.show(d));   ③  //A and D    A.show(D)-->AD        System.out.println(a2.show(b));   ④  //B and A    A.show(B)-->super.show(B)-->A.show(super(B))-->new B.show(super(B))        System.out.println(a2.show(c));   ⑤  //B and A    A.show(B)-->super.show(C)-->A.show(super(C))-->A.show(super(super(C)))-->new C.show(super(super(c)))-->BA  C中有重写show(A)方法        System.out.println(a2.show(d));   ⑥  //A and D    A.show(D)-->AD   D中没有重写show(D)方法        System.out.println(b.show(b));    ⑦  //B and B    B.show(B)-->BB        System.out.println(b.show(c));    ⑧  //B and B    B.show(C)-->super.show(C)-->B.show(super(C))-->BB        System.out.println(b.show(d));    ⑨  //A and D    B.show(D)-->super.show(D)-->AD
分析:实际上这里涉及方法调用的优先问题 ,优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)

方法的调用是由引用对象所指向的真正对象所确定的,不是传递的参数决定的。例如 A a2 = new B(); System.out.println(a2.show(c)); 是由new B决定的,而不是A也不是c。

也就是说,先在A中存在该方法,且B中也存在,那么调用B中的;当A中存在,B中不存在,调用A中的。


0 0
原创粉丝点击