Java中instanceof与类型转换
1.新建Person类
public class Person {
public void run ( ) {
System . out. println ( "run" ) ;
}
}
2.新建Student类
public class Student extends Person {
public void go ( ) {
System . out. println ( "go" ) ;
}
}
3.新建Teacher类
public class Teacher extends Person {
}
4.新建Application类,作为程序的入口
public class Application {
public static void main ( String [ ] args) {
Person s1 = new Student ( ) ;
Student s2 = ( Student ) s1;
s2. go ( ) ;
Student s3 = new Student ( ) ;
s3. go ( ) ;
s3. run ( ) ;
Person s4 = new Student ( ) ;
s4. run ( ) ;
( ( Student ) s4) . go ( ) ;
System . out. println ( "===================" ) ;
Object obj = new Student ( ) ;
System . out. println ( obj instanceof Student ) ;
System . out. println ( obj instanceof Person ) ;
System . out. println ( obj instanceof Object ) ;
System . out. println ( obj instanceof Teacher ) ;
System . out. println ( obj instanceof String ) ;
System . out. println ( "===============" ) ;
Person person = new Person ( ) ;
System . out. println ( person instanceof Person ) ;
System . out. println ( person instanceof Object ) ;
System . out. println ( person instanceof Student ) ;
System . out. println ( person instanceof Teacher ) ;
System . out. println ( "===============" ) ;
Student student = new Student ( ) ;
System . out. println ( student instanceof Person ) ;
System . out. println ( student instanceof Object ) ;
System . out. println ( student instanceof Student ) ;
}
}
多态
1. 父类的引用指向子类的对象(子类的引用不能指向父类的对象)
2. 把子类转换为父类,向上转型
3. 把父类转换为子类,向下转换;强制转换
4. 方便方法的调用,减少重复的代码,简洁