Java-多态性(虚拟方法的调用)
1.概念
- 可以理解为一个事务的多种形态
- 父类的引用指向子类的对象(子类的对象赋给父类的引用)
- 多态的使用,虚拟方法调用,有了对象的多态性以后,我们在编译期,只能调用父类中声明的方法,但在运行期,我们实际执行的是重写父类的方法。(
编译=的左边,运行看右边 ) - 对象的多态性,只适用于方法,不适用于属性(
属性在编译和运行的情况下都看左边 )
2.多态使用的前提
3.code 举例
-
父类Animal类 package com.lmwei.p12;
public class Animal {
protected int id = 1001;
public void eat() {
System.out.println("动物,进食");
}
public void shout() {
System.out.println("动物,叫");
}
}
-
子类Dog 类 package com.lmwei.p12;
public class Dog extends Animal{
protected int id = 1002;
@Override
public void eat() {
System.out.println("狗吃骨头");
}
@Override
public void shout() {
System.out.println("汪汪汪");
}
}
-
子类Cat类 package com.lmwei.p12;
public class Cat extends Animal{
public Cat() {
}
@Override
public void eat() {
System.out.println("猫吃,鱼");
}
@Override
public void shout() {
System.out.println("喵喵喵");
}
}
-
测试类 package com.lmwei.p12;
public class AnimalTest {
public void func(Animal animal) {
animal.eat();
animal.shout();
System.out.println(animal.id);
}
public static void main(String[] args) {
AnimalTest a = new AnimalTest();
a.func(new Dog());
System.out.println("---------------------------------------------------------");
a.func(new Cat());
}
}
4.虚拟方法的调用
以下代码证明多态是一个运行时行为:
package com.lmwei.tets;
import java.util.Random;
class Animal {
protected void eat() {
System.out.println("animal eat food");
}
}
class Cat extends Animal {
protected void eat() {
System.out.println("cat eat fish");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog eat bone");
}
}
class Sheep extends Animal {
public void eat() {
System.out.println("Sheep eat grass");
}
}
public class InterviewTest {
public static Animal getInstance(int key) {
switch (key) {
case 0:
return new Cat ();
case 1:
return new Dog ();
default:
return new Sheep ();
}
}
public static void main(String[] args) {
int key = new Random().nextInt(3);
System.out.println(key);
Animal animal = getInstance(key);
animal.eat();
}
}
|