1.多态的定义
2.多态的使用
//父类 public class Person { String name; int age=18; int id=1001; public void eat() { System.out.println("人 : 吃饭"); } public void walk() { System.out.println("人 : 走路"); } } //子类1 public class Man extends Person{ boolean isSmoking; int id=1002; public void earnMoney() { System.out.println("男人负责挣钱养家"); } public void eat() { System.out.println("男人 : 多吃吃饭"); } public void walk() { System.out.println("男人 : 多走走路"); } } //子类2 ublic class Woman extends Person{ boolean isBeauty; public void goShopping() { System.out.println("女人喜欢购物"); } public void eat() { System.out.println("女人 : 少吃吃饭"); } public void walk() { System.out.println("女人 : 少走走路"); } } //测试类 public class PersonTest { public static void main(String[] args) { //非多态 Person p1 = new Person(); p1.eat(); Man man1 = new Man(); man1.age=25; man1.earnMoney(); System.out.println("**********************************************"); //多态 : 父类引用指向子类对象 Person p2 = new Man(); // 只能调用 子类重写过的方法 // 注 : 编译看左 , 运行看右 (当你ctrl点击p2.eat()方法时 , 会发现进入了Person类) p2.eat(); p2.walk(); Person p3 = new Woman(); p3.eat(); p3.walk(); System.out.println(p2.id);// 1001 说明 : java的多态性 只适用于方法 , 不适用于属性. } }
3.为什么要有多态 ?
//多态举例 public class AnimalTest { public static void main(String[] args) { AnimalTest test = new AnimalTest(); //多态性 test.method1(new Dog()); test.method1(new Cat()); } //多态性 public void method1(Animal animal) { animal.eat(); animal.shout(); } //若无多态性 ( 如果有几十个子类 , 岂不是要重载几十次method1方法 ? ) public void method1(Dog dog) { dog.eat(); dog.shout(); } public void method1(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("汪!汪!汪"); } } class Cat extends Animal { public void eat() { System.out.println("猫吃鱼"); } public void shout() { System.out.println("喵!喵!喵"); } }
总结 : 因为有了多态 , 可以少写很多重复性的代码 !