java面向对象- 多态性的体现和使用

  1. 多态体现:

        方法的重载和重写

        对象的多态性


2.对象的多态性:

        向上转型:程序会自动完成

            父类 父类对象 = 子类实例

        向下转型:强制类型转换

            子类 子类对象 = (子类)父类实例       

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class  A{
     public  void  tell01(){
         System.out.println( "A--tell01" );
     }
     public  void  tell02(){
         System.out.println( "A--tell02" );
     }
}
 
class  extends  A{
     public  void  tell01(){
         System.out.println( "B--tell01" );
     }
     public  void  tell03(){
         System.out.println( "B--tell03" );
     }
}
 
public  class  PolDemo01 {
 
     public  static  void  main(String[] args) {
         //向上转型
//      B b = new B();
//      A a = b;
//      a.tell01();//tell01重写的
//      a.tell02();
         //向下转型
         A a =  new  B();
         B b = (B)a;
         b.tell01();
         b.tell02();
         b.tell03();
     }
 
}

运行结果:

       向上转型:                                  向下转型:

            B--tell01                                   B--tell01

            A--tell02                                   A--tell02

                                                        B--tell03

            


3.对象多态性的使用:       

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class  A1{
     public  void  tell01(){
         System.out.println( "A--tell01" );
     }
}
 
class  B1  extends  A1{
     public  void  tell02(){
         System.out.println( "B--tell02" );
     }
}
 
class  C1  extends  A1{
     public  void  tell03(){
         System.out.println( "C--tell03" );
    
}
 
class  D1  extends  A1{
     
}
 
public  class  PolDemo02 {
 
     public  static  void  main(String[] args) {
         say( new  B1());
         say( new  C1());
         say( new  D1());
     }
     
     public  static  void  say(A1 a){
         a.tell01();
     }
 
}

执行结果:    

    A--tell01

    A--tell01

    A--tell01


本文转自yeleven 51CTO博客,原文链接:http://blog.51cto.com/11317783/1757222