package com.day12.Polymorphism;
public class PersonTest3 {
//方法可以接收任意Person及子类对象,兼容性提高了
public static void test(Person p) {//接收对象,参数就是父类类型的,这样的方法称为多态参数方法
p.sayHello();
//p.spring();多态副作用
//instanceof 判断左侧引用指向对象的实体是否是 右侧的类型的一个对象,如果是,返回true,不是返回false
if (p instanceof Beijing) {
System.out.println("北京人");
} else if (p instanceof Chinese) {
Chinese ch = (Chinese) p;//造型 造型有风险!!必须先判断
ch.spring();
} else if (p instanceof American) {
((American) p).christmas();
} else {
System.out.println("普通人");//顺序很重要,大范围在下,小范围在上
}
}
public static void main(String[] args) {
Chinese ch = new Chinese("张三", 30, "男", "虎");
American am = new American("Banner", 20, "male", true);
Person p = new Person("someBody", 25, "unknown");
Beijing bj = new Beijing("李四", 40, "女", "猪");
test(bj);
}
}
public class ComputerTest2 {
public static void listPrice(Computer com){
System.out.println(com.getPrice());
if(com instanceof PC ){
PC pc = (PC) com;
pc.code();
}else if (com instanceof NotePad){
((NotePad)com).navigate();
}else{
System.out.println("普通电脑");
}
}
public static void main(String[] args) {
listPrice(new NotePad(2.6, 16, 400, 8999, 8));
listPrice(new PC(3.5, 8, 500, 3999, "cherry"));
listPrice(new Computer(3, 4, 300, 2000));
}
}