# 多态

对象的多种形态。引用多态、方法多态。

TIP

继承是多态实现的基础

# 引用多态

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

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

# 方法多态

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

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

// Animal.java
package com.polymorphic;

public class Animal {
	public void eat () {
		System.out.println("Animal has eat method.");
	}
}
1
2
3
4
5
6
7
8
// Dog.java
package com.polymorphic;

public class Dog extends Animal {
	// overwrite
	public void eat () {
		System.out.println("Dogs eat meat.");
	}
}
1
2
3
4
5
6
7
8
9
// Cat.java
package com.polymorphic;

public class Cat extends Animal {

}
1
2
3
4
5
6
// Initial.java
package com.polymorphic;

public class Initial {

	public static void main(String[] args) {
		/*
		 * 引用多态/方法多态
		 */
		// 父类的引用可以指向本类的对象
		Animal obj1 = new Animal();
		// 父类的引用可以指向子类的对象
		Animal obj2 = new Dog();
		Animal obj3 = new Cat();
		// methods polymorphic
		obj1.eat();
		obj2.eat();
		obj3.eat();
		/*
		 * 引用类型转换
		 */
		Dog dog = new Dog();
		Animal animal = dog; // 自动类型提升,向上类型转换
		// Warning
		// Dog dog2 = animal; // Type mismatch: cannot convert from Animal to Dog
		Dog dog2 = (Dog)animal; // 向下类型转换 强制类型转换
		// error
		// Cat cat = (Cat)animal; // 编译时Cat类型(不会报错),运行时Dog类型(抛出异常)
		// instanceof
		if (animal instanceof Cat) {
			Cat cat = (Cat)animal;
		} else {
			System.out.println("无法进行Cat类型转换");
		}
	}

}
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
36
37

# 多态中的引用类型转换

向上类型转换(隐式/自动类型转换),是小类型到大类型的转换。

向下类型转换(强制类型转换),是大类型到小类型。容易发送数据溢出。

instanceof运算符,来解决引用对象的类型,避免类型转换的安全性问题。

package com.polymorphic;

public class Initial {

	public static void main(String[] args) {
		/*
		 * 引用多态/方法多态
		 */
		// 父类的引用可以指向本类的对象
		Animal obj1 = new Animal();
		// 父类的引用可以指向子类的对象
		Animal obj2 = new Dog();
		Animal obj3 = new Cat();
		// methods polymorphic
		obj1.eat();
		obj2.eat();
		obj3.eat();
		/*
		 * 引用类型转换
		 */
		Dog dog = new Dog();
		Animal animal = dog; // 自动类型提升,向上类型转换
		// Warning
		// Dog dog2 = animal; // Type mismatch: cannot convert from Animal to Dog
		Dog dog2 = (Dog)animal; // 向下类型转换 强制类型转换
		// error
		// Cat cat = (Cat)animal; // 编译时Cat类型(不会报错),运行时Dog类型(抛出异常)
		// instanceof
		if (animal instanceof Cat) {
			Cat cat = (Cat)animal;
		} else {
			System.out.println("无法进行Cat类型转换");
		}
	}

}
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
36