Test类
public class Test {
public static void main(String[] args) {
Person p = Ghost.catchPerson(0);
Ghost.eatPerson(p);
}
}
Person类
public class Person {
String name;
protected void say(){
System.out.println("Person的say...");
}
public Person(){
}
public Person(String name){
this.name = name;
}
}
Ghost类
public class Ghost {
//返回值类型多态
public static Person catchPerson(int choice){
Person p = null;
switch(choice){
case 0:
p = new Teacher();
break;
case 1:
p = new Stu();
break;
case 2:
p = new Officer();
break;
default:
p = new Person();
}
return p;
}
//参数类型多态
public static void eatPerson(Person p){
p.say();
//Instanceof判断左边变量所指向的实际类型是否为右边类型的对象或右边类型子类的对象
if(p instanceof Stu){
Stu s = (Stu)p;
s.play();
}
if (p instanceof Teacher)
{
Teacher t = (Teacher)p;
t.play();
}
}
}
Teacher类(继承Person)
public class Teacher extends Person {
public void say(){
System.out.println("教学中,能不能不吃...");
}
public void play()
{
System.out.println("我在上课");
}
}
Student类(继承Person)
public class Stu extends Person {
protected void say(){
System.out.println("游戏中,等会再吃...");
}
public void play(){
System.out.println("吃鸡中...");
}
}
Office类(继承Person)
public class Officer extends Person {
public void say(){
System.out.println("贪污这么多,还是不够花...");
}
}