多态时运行时行为
下面用代码来证明
思路:
定义一个随机数,打印一下(方便比较)
接下来调用一下getInstance方法,方法中switch case 根据随机数不同,new 不同的对象。然后返回赋值给Animal。然后调用eat方法。
package com.ifengtest.java;
//面试题多态时运行时行为,还是编译时行为?答案:运行时行为
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{
protected void eat(){
System.out.println("dog eat shit");
}
}
class Sheep extends Animal{
protected void eat(){
System.out.println("sheep eat grass");
}
}
public class InterviewTest{
public static void main(String [] args){
int key = new Random().nextInt(3);
System.out.println(key);
Animal animal = getInstance(key);//看不出结果,是运行时行为,只有运行时的时候才知道new的对象是什么
animal.eat();
}
public static Animal getinstance(int key){
swith (key){
case 0:
return new Cat();
case 1:
return new Dog();
default:
return new Animal();
}
}