面试题:多态是编译时行为还是运行时行为?
先给出答案,多态是运行时行为
本题主要是考察对多态性的理解
关于多态性的理解后面我会写一篇文章来阐述一下
下面引用一段代码来证明此答案
package com.codediao.java5;
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);// 看不出来结果,是运行时行为,只有运行的时候才知道new的是谁
animal.eat();
}
}