1. 多态
-
多态polymorhic概述
- 事物存在的多种形态。
- 多态前提
- 要有继承关系
- 要有方法重写
- 要有父类引用指向子类对象
- 案例演示
- 代码体现多态
-
class Demo1_Polymorphic{ public static void main(String[] args) { Cat c = new Cat(); c.eat(); Animal a = new Cat(); // 父类引用指向子类对象 a.eat(); // 输出“猫吃鱼” } } class Animal { public void eat() { System.out.println("动物吃饭"); } } class Cat extends Animal { public void eat() { System.out.println("猫吃鱼"); } }
- 多态中的成员访问特点
- 成员变量
- 编译看左边(父类),运行看左边(父类)
- Father f = new Son();
-
class Demo2_Polymorphic { public static void main(String[] args) { Father f = new Son(); System.out.println(f.num); //输出10 } } class Father { int num = 10; } class Son extends Father { int num = 20; }
如果再上面例子的基础上,再生成一个Son类对象,则
-
class Demo2_Polymorphic { public static void main(String[] args) { Father f = new Son(); System.out.println(f.num); //输出10 Son s = new Son(); System.out.println(s.num); //输出20 } } class Father { int num = 10; } class Son extends Father { int num = 20; }
- 成员方法
- 编译看左边(父类),运行看右边(子类)——又称“动态绑定”
- Father f = new Son();
- 编译时,看父类中有没有该成员方法,有则编译成功;运行则动态绑定到子类的成员方法上,运行子类的成员方法。
-
class Demo3_Polymorphic { public static void main(String[] args) { Father f = new Son(); f.print();// 输出son } } class Father { int num = 10; public void print() { System.out.println("father"); } } class Son extends Father { int num = 20; public void print() { System.out.println("son"); } }
- 静态方法
- 编译看左边(父类),运行看左边(父类)
- 静态和类相关,算不上重写,所以,访问还是左边的
-
class Demo4_Polymorphic { public static void main(String[] args) { Father f = new Son(); f.method(); //输出"father static method"; // 相当于是Father.method(); 调用父类的方法 } } class Father { int num = 10; public void print() { System.out.println("father"); } public static void method(){ System.out.println("father static method"); } } class Son extends Father { int num = 20; public void print() { System.out.println("son"); } public static void method(){ System.out.println("son static method"); } }
- 总结:
- 只有非静态的成员方法,编译看左边(父类),运行看右边(子类)
- 其他都是编译看左边(父类),运行看左边(父类)
- 成员变量
- 案例:超人的故事
- 通过该案例帮助理解多态的现象。
-
View Code
class Demo5_Polymorphic { public static void main(String[] args) { Person p = new SuperMan(); // 父类引用指向子类对象,超人提升为人 System.out.println(p.name);// 输出“John” p.谈生意(); // 输出"谈几个亿的大单子" //p.fly(); //编译出错 } } class Person { String name = "John"; public void 谈生意() { System.out.println("谈生意"); } } class SuperMan extends Person { String name = "Super man"; public void 谈生意() { System.out.println("谈几个亿的大单子"); } public void fly() { System.out.println("飞出去救人"); } }