instanceof和类型转换
instanceof 判断类型是否相似,只要有继承关系,instanceof就为true 例子:
package oop. dome9;
public class Person {
public void run ( ) {
System. out. println ( "run" ) ;
}
}
package oop. dome9;
public class Student extends Person {
public void go ( ) {
System. out. println ( "go" ) ;
}
}
package oop. dome9;
public class Teacher extends Person {
}
package oop;
import oop. dome9. Person;
import oop. dome9. Student;
import oop. dome9. Teacher;
public class Application {
public static void main ( String[ ] args) {
Object object = new Student ( ) ;
System. out. println ( object instanceof Student ) ;
System. out. println ( object instanceof Person ) ;
System. out. println ( object instanceof Object ) ;
System. out. println ( object instanceof Teacher ) ;
System. out. println ( object instanceof String ) ;
System. out. println ( "================================================" ) ;
Person person = new Student ( ) ;
System. out. println ( person instanceof Student ) ;
System. out. println ( person instanceof Person ) ;
System. out. println ( person instanceof Object ) ;
System. out. println ( person instanceof Teacher ) ;
System. out. println ( "================================================" ) ;
Student student = new Student ( ) ;
System. out. println ( student instanceof Student ) ;
System. out. println ( student instanceof Person ) ;
System. out. println ( student instanceof Object ) ;
/ 类型之间的转化:父————> 子
Person obj = new Student ( ) ;
Student student = ( Student) obj;
student. go ( ) ;
}
}