11.多态

对象的多种形态

1.引用形态

父类的引用可以指向本类的对象

父类的引用可以指向子类的对象

Animal d=new Animal();

Animal d2=new Dog();  //父类变量不能引用子类的对象

但是Dog d2=new Animal();就是错的  子类变量不能引用父类的对象

2.方法多态

创建本类对象时,调用的方法为本类方法

创建子类对象时,调用的方法为子类重写的方法或者继承的方法

public class Cat extends Animal {

}

public class Initial {

public static void main(String[] args) {

Animal d=new Animal();

Animal d2=new Dog();

Animal d3=new Cat();

d.eat();

d3.watchddor();// 这是不行的  ,因为watchdoor是子类专有的方法 

d3.eat();//虽然d3 cat类里面什么也没有,但是因为多态的原因 它会调用父类的方法

}

}

```

publicclassA{

publicStringshow(D obj){

return("A and D");

        } 


publicStringshow(A obj){

return("A and A");

        } 


    } 


publicclassBextendsA{

publicStringshow(B obj){

return("B and B");

        } 


publicStringshow(A obj){

return("B and A");

        } 

    } 


publicclassCextendsB{


    } 


publicclassDextendsB{


    } 


publicclassTest{

publicstaticvoidmain(String[] args){

A a1 =newA();

A a2 =newB();

B b =newB();

C c =newC();

D d =newD();


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));//4--B and A .首先a2是A引用,B实例,调用show(B b)方法,此方法在父类A中没有定义,所以B中方法show(B b)不会调用(多态必须父类中已定义该方法),再按优先级为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O),即先查this对象的父类,没有重头再查参数的父类。查找super.show((super)O)时,B中没有,再向上,找到A中show(A a),因此执行。

System.out.println("5--"+ a2.show(c));//同上

System.out.println("6--"+ a2.show(d));//A and D .查找B中没有show(D d)方法,再查A中,有,执行。

System.out.println("7--"+ b.show(b));

System.out.println("8--"+ b.show(c));//B and B .

System.out.println("9--"+ b.show(d));

        } 

    }

```

```

1--A and A

2--A and A

3--A and D

4--B and A

5--B and A

6--A and D

7--B and B

8--B and B

9--A and D

```

你可能感兴趣的:(11.多态)