/*
* 面向对象特征之三:多态性
*
* 1.理解多态性:可以理解为一个事物的多种形态。
* 2.何为多态性:
* 对象的多态性:父类的引用指向子类的对象(或子类的对象赋给父类的引用)
*
* 3. 多态的使用:虚拟方法调用
* 有了对象的多态性以后,我们在编译期,只能调用父类中声明的方法,但在运行期,我们实际执行的是子类重写父类的方法。
* 总结:编译,看左边;运行,看右边。
*
* 4.多态性的使用前提: ① 类的继承关系 ② 方法的重写
*
* 5.对象的多态性,只适用于方法,不适用于属性(编译和运行都看左边)
*/
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.eat();
Man man = new Man();
man.eat();
man.age = 25;
man.earnMoney();
//*************************************************
System.out.println("*******************");
//对象的多态性:父类的引用指向子类的对象
Person p2 = new Man();
// Person p3 = new Woman();
//多态的使用:当调用子父类同名同参数的方法时,实际执行的是子类重写父类的方法 ---虚拟方法调用
p2.eat();
p2.walk();
// p2.earnMoney();
System.out.println(p2.id);//1001
}
}
package com.ch.java4;
import java.sql.Connection;
//多态性的使用举例一: public class AnimalTest { public static void main(String[] args) { AnimalTest test = new AnimalTest(); test.func(new Dog()); //此时调用的func中的eat,shout方法变现为子类中dog重写的eat,shout方法 test.func(new Cat()); //此时调用的func中的eat,shout方法变现为子类中cat中重写的eat,shout方法 } public void func(Animal animal) { //Animal animal = new Dog(); animal.eat(); animal.shout(); if (animal instanceof Dog) { Dog d = (Dog) animal; d.watchDoor(); } } //如果没有多态性,就得自己另外写两个方法 // public void func(Dog dog){ // dog.eat(); // dog.shout(); // } // public void func(Cat cat){ // cat.eat(); // cat.shout(); // } } class Animal { public void eat() { System.out.println("动物:进食"); } public void shout() { System.out.println("动物:叫"); } } class Dog extends Animal { public void eat() { System.out.println("狗吃骨头"); } public void shout() { System.out.println("汪!汪!汪!"); } public void watchDoor() { System.out.println("看门"); } } class Cat extends Animal { public void eat() { System.out.println("猫吃鱼"); } public void shout() { System.out.println("喵!喵!喵!"); } } //举例二: class Order { public void method(Object obj) { } } //举例三: class Driver { public void doData(Connection conn) { //conn = new MySQlConnection(); / conn = new OracleConnection(); //规范的步骤去操作数据 // conn.method1(); // conn.method2(); // conn.method3(); } }
面向对象特征之三:多态性(方法的多态性,属性不存在多态性,都决定于左边父类的属性)
原文:https://www.cnblogs.com/CCTVCHCH/p/14584957.html