instanceof运算符:
例如:p instanceof Man:判断p引用指向的对象,是不是Man的本类类型及子类类型
避免ClassException错误的发生
public class ploymorphismTest4 {
public static void main(String[] args) {
show(new Man());
Person p=new Woman();
show(p);
Student stu=new Student();
show(stu);
//show(new Man());
}
/*//需求:展示一个男人吃饭走路的功能
public static void show(Man man){
man.eat();
man.walk();
}
//需求:展示一个女人吃饭走路的功能
public static void show(Woman woman){
woman.eat();
woman.walk();
}
//需求:展示一个学生吃饭走路的功能
public static void show(Students students){
students.eat();
students.walk();
}
*/
public static void show(Person p){//p:多态参数
p.eat();
p.walk();
//调用特有方法
if(p instanceof Man){
Man man=(Man)p;//强转
Man.smoking();
}
}
class Person{
private String name;
private int age;
public Person(){
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
//吃饭
public void eat(){
System.out.println("吃饭");
}
//走路
public void walk(){
System.out.println("走路");
}
}
class Man extends Person{
boolean mustache;//是否有胡子
public void eat(){
System.out.println("男人吃饭狼吞虎咽");
}
public void walk(){
System.out.println("男人走正步");
}
//男人特有功能
public void smoking(){
System.out.println("男人爱抽烟");
}
}
class Woman extends Person{
boolean beauty;
public void eat(){
System.out.println("女人吃饭细嚼慢咽");
}
public void walk(){
System.out.println("女人走猫步");
}
public void shopping(){
System.out.println("女人爱购物");
}
}
class Students extends Person{
public void eat(){
System.out.println("学生吃食堂");
}
public void walk(){
System.out.println("学生蹦蹦跳跳的走");
}
public void study(){
System.out.println("学习");
}
}
}
{
}