Java引用变量有两种类型:一个是编译时的类型,一个是运行时的类型。当两个类型不一致时,就产生了多态。

 1 class  DuoTaiDemo 
 2 {        
 3     public static void function(Cat cat1) 
 4     { 
 5         cat1.eat(); 
 6     } 
 7     public static void main(String[] args)  
 8     { 
 9         function(new Cat()); 
10     } 
11 } 
12 abstract class Animal 
13 { 
14     abstract void eat(); 
15   
16 } 
17 class Cat extends Animal 
18 { 
19     public void eat() 
20     { 
21         System.out.println("吃鱼"); 
22     } 
23 } 
24 class Dog extends Animal 
25 { 
26     public void eat() 
27     { 
28         System.out.println("吃骨头"); 
29     } 
30   
31 }
32 /*
33 如果我们以后想要添加一个猪(pig)的类必须再添加一个方法
34 我们可以将function方法改为 
35     public static void function(Animal animal) 
36     { 
37         animal.eat(); 
38     } 
39 
40 */

 编写Java程序时,引用变量只能调用它编译时类型的方法,而不能调用运行时的方法。如果需要这个引用变量来调用它运行时类型的方法,则必须把它强制类型转换成运行时类型。

引用类型之间的转换只能把一个父类变量转换成子类类型。没有任何继承关系的类型,则无法进行类型转换。

 

 1 class DuoTaiDemo2 
 2 {
 3     public static void main(String[] args) 
 4     {
 5         Parent p=new Child();
 6         p.show();//子类方法一
 7         ((Child)p).show_1();//子类方法二
 8     }
 9 }
10 class Parent
11 {
12     public void show()
13     {
14         System.out.println("父类方法!");
15     }
16 }
17 class Child extends Parent
18 {
19     public void show()
20     {
21         System.out.println("子类方法一!");
22     }
23     public void show_1()
24     {
25         System.out.println("子类方法二");
26     }
27 }
  • instanceof运算符

考虑到进行强制转换可能出席那异常,因此进行类型转换之前应先通过instanceof运算符来判断是否可以转换成功

1         if (p instanceof Child)
2         {
3             Child c=(Child)p;
4             c.show_1();
5         }

 

 

posted on 2012-06-04 15:37  Lincon Ma  阅读(118)  评论(0编辑  收藏  举报