长辈们常说:人啊,什么时候都不能够忘本。
经过上两篇this和super的讲解,可以让自己知道什么调用自己的方法和成员,什么时候调用父类的方法和成员,那么对外人来说,如何区分一个对象到底是父类还是某个子类的实例呢?Java中关键字instanceof是专门为此而生的。当一个子类的实例赋值给一个父类的变量,这是Java多态的一种表现。而有时我们又想知道它到底是谁。
在this那一讲有个父类叫Student,super那一讲加了一个子类叫ClassLeader,今天在加一个子类叫生活委员吧,Lifeleader。Chinese英语只为做demo,勿怪。
public class LifeLeader extends Student { private int fare; public LifeLeader(String name,String college,int fare) { super(name,college); this.fare = fare; } public void print() { super.print(); System.out.println("fare is " + fare); } public static void main(String[] args) { Student linc = new LifeLeader("linc","shenyang",500); Student lily = new ClassLeader("class monitor","lily","shenyang"); whoAreYou(linc); whoAreYou(lily); } public static void whoAreYou(Student student) { if(student instanceof ClassLeader) { System.out.println("this is ClassLeader!"); student.print(); } else if(student instanceof LifeLeader) { System.out.println("this is LifeLeader!"); student.print(); } } }编译运行:
D:\workspace\Java\project261\instance>javac -d . *java D:\workspace\Java\project261\instance>java LifeLeader construct this student name is linc this student name is linc college is shenyang construct this student name is lily this student name is lily college is shenyang this is LifeLeader! name is: linc age is: 20 college is: shenyang fare is 500 this is ClassLeader! name is: lily age is: 20 college is: shenyang duty is class monitor