Example:    Class Teacher and Student are subclass of class Person. 
    Person p; 
    Teacher t; 
    Student s; 
    p, t and s are all non-null. 
    if(t instanceof Person) {  s = (Student)t; } 
What is the result of this sentence? 
A. It will construct a Student object. 
B. The expression is legal. 
C. It is illegal at compilation. 
D. It is legal at compilation but possible illegal at runtime. 
(c)
  instanceof操作符的作用是判断一个变量是否是右操作数指出的类的一个对象,由于java语言的多态性使得可以用一个子类的实例赋值给一个 
父类的变量,而在一些情况下需要判断变量到底是一个什么类型的对象,这时就可以使用instanceof了。当左操作数是右操作数指出的类的实 
例或者是子类的实例时都返回真,如果是将一个子类的实例赋值给一个父类的变量,用instanceof判断该变量是否是子类的一个实例时也将返 
回真。此题中的if语句的判断没有问题,而且将返回真,但是后面的类型转换是非法的,因为t是一个Teacher对象,它不能被强制转换为一个 
Student对象,即使这两个类有共同的父类。如果是将t转换为一个Person对象则可以,而且不需要强制转换。这个错误在编译时就可以发现, 
因此编译不能通过。
   
 
  |