Java学习笔记之多态

1.父类型的引用可以指向子类型的对象:

  Parent p = new Child();

2.当使用多态方式调用方法时,首先检查父类中是否有该方法,如果没有,则编译错误;如果有,再去调用子类的该同名方法。

3.静态static方法属于特殊情况,静态方法只能继承,不能重写Override,如果子类中定义了同名同形式的静态方法,它对父类方法只起到隐藏的作用。调用的时候用谁的引用,则调用谁的版本。

4.使用多态,只能使用重写父类的方法,若方法只在父类定义而没有重写,调用的是父类的方法。

5.如果想要调用子类中有而父类中没有的方法,需要进行强制类型转换,如上面的例子中,将p转换为子类Child类型的引用。

6.向上类型转换(Upcast):将子类型转换为父类型,不需要显示指定,即不需要加上前面的小括号和父类类型名。

7.向下类型转换(Downcast):将父类型转换为子类型;对于向下的类型转换,必须要显式指定,即必须要使用强制类型转换。并且父类型的引用必须指向子类的对象,即指向谁才能转换成谁。

9.示例:

 1 public class PolyTest
 2 {
 3     public static void main(String[] args)
 4     {
 5         
 6         //向上类型转换
 7         Cat cat = new Cat();
 8         Animal animal = cat;
 9         animal.sing();
10 
11                 
12         //向下类型转换
13         Animal a = new Cat();
14         Cat c = (Cat)a;
15         c.sing();
16         c.eat();
17 
18 
19         //编译错误
20         //用父类引用调用父类不存在的方法
21         //Animal a1 = new Cat();
22         //a1.eat();
23         
24         //编译错误
25         //向下类型转换时只能转向指向的对象类型        
26         //Animal a2 = new Cat();
27         //Cat c2 = (Dog)a2;
28         
29 
30 
31     }
32 }
33 class Animal
34 {
35     public void sing()
36     {
37         System.out.println("Animal is singing!");
38     }
39 }
40 class Dog extends Animal
41 {
42     public void sing()
43     {
44         System.out.println("Dog is singing!");
45     }
46 }
47 class Cat extends Animal
48 {
49     public void sing()
50     {
51         System.out.println("Cat is singing!");
52     }
53     public void eat()
54     {
55         System.out.println("Cat is eating!");
56     }
57 }
View Code
原文地址:https://www.cnblogs.com/qingyibusi/p/5770748.html