多态是运行时行为(面试题)

面试题:多态是编译时行为还是运行时行为?

运行时行为

证明如下:
测试类
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);//随机数0、1、2

		System.out.println(key);

		Animal  animal = getInstance(key);
		
		animal.eat();
		 
	}

}
父类和子类

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");

	}

 
}

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/113600087