1.定义
某一事物具有多种存在形态
2.代码体现
父类或者接口的引用指向其子类的对象
3.好处及弊端
提高代码的扩展性,前期定义的代码可以使用后期的内容
前期定义的内容不能调用后期子类的特有内容
4.转型
对于转型,始终都是子类对象在做着类型的变化
代码示例:
abstract class Animal {
abstract void eat();
}
class Dog extends Animal {
void eat() {
System.out.println("狗粮");
}
void lookHome() {
System.out.println("看家");
}
}
class Cat extends Animal {
void eat() {
System.out.println("猫粮");
}
void catchMouse() {
System.out.println("抓老鼠");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Animal a1 = new Cat();// 自动类型提升,猫对象提升了动物类型,但特有功能无法访问,限制对特有功能的访问 向上转型
a1.eat();
Cat c = (Cat) a1;// 如果使用猫的特有功能,可将该对象 向下转型
c.eat();
c.catchMouse();
Animal a2 = new Dog();
method(a2);
}
public static void method(Animal a) {
a.eat();
if (a instanceof Dog) {// instaceof:用于判断对象的具体类型,只能用于引用数据类型的判断
Dog d = (Dog) a;
d.lookHome();
}
}
}
5.成员特点
成员变量:
编译时:参考引用型变量所属的类中是否有调用的成员变量。如果有,编译通过,否则编译失败。
运行时:参考引用型变量所属的类中是否有调用的成员变量,并运行该所属类中的成员变量。
编译和运行时都看左边
成员函数(非静态):
编译时:参考引用变量所属的类中是否有所调用的函数,如果有则编译通过,否则编译失败
运行时:参考对象所属的类中是否有所调用的函数。
编译时看左边,运行时看右边
代码示例:
class Fu {
int num = 3;
void show() {
System.out.println("fu show");
}
}
class Zi extends Fu {
int num = 4;
void show() {
System.out.println("zi show");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Fu f = new Zi();
System.out.println(f.num);
f.show();
}
}
静态函数:
不需要对象,直接用类名调用,不涉及多态
代码示例:
class Fu {
static void method() {
System.out.println("fu static method");
}
}
class Zi extends Fu {
static void method() {
System.out.println("zi static method");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Fu f = new Zi();
f.method();
}
}