1.何为多态性?
对象的多态性:父类的引用指向子类的对象(或子类的对象赋给父类的引用)
2.多态的使用:虚拟方法调用
有了对象的多态性以后,我们在编译器,只能调用父类中声明的方法,在运行期实际执行的时候,执行的是子类重写的方法
3.多态性的使用前提:
3.1.要有类的继承关系
3.2.要有方法的重写
class Person{ int age; public void eat(){ System.out.println("eat!"); } } class Man extends Person{ public void eat(){ System.out.println("eat shit"); } public void earnMoney(){ System.out.println("earn!"); } } public class PersonTest{ public static void main(String[] args){ Person p = new Man(); //注意!new 的是 Man ! p.eat(); //p.earnMoney(); //无法调用 } }
4.多态性的举例:
package e1; public class AnimalTest { public static void main(String[] args) { AnimalTest animalTest = new AnimalTest(); animalTest.func(new Dog()); //运行的时候是执行Dog的方法 animalTest.func(new Cat()); //运行的时候是执行Cat的方法 } public void func(Animal animal){ //相当于:Animal animal = new Dog(); animal.eat(); animal.shout(); } } class Animal{ public void eat(){ System.out.println("animal eat"); } public void shout(){ System.out.println("animal shout"); } } class Dog extends Animal{ public void eat(){ System.out.println("dog eat"); } public void shout(){ System.out.println("dog bark"); } } class Cat extends Animal{ public void eat(){ System.out.println("Cat eat"); } public void shout(){ System.out.println("Cat wangwang"); } }
5.对象的多态性只适用于方法,不适用于属性!!
public class PersonTest { public static void main(String[] args) { Person p = new Student(); System.out.println(p.id); //这时候输出的是父类中的属性!! //1001 } } class Person{ int id = 1001; } class Student extends Person{ int id = 1002; }
对于重载,在方法调用之前,编译器就已经确定了所要调用的方法!!
对于多态,只有等到方法调用的那一刻,解释运行器才会确定索要调用的具体方法!!
posted on
浙公网安备 33010602011771号