Java基础学习:面向对象13( instanceof )
-
instanceof 和 类型转换:
-
判断一个对象是什么类型:instanceof;(判断2个类之间是否存在父子关系)
-
-
总结:
-
代码案例:
?
public class Application {
public static void main(String[] args) {
?
//类型之间的转换:基本类型转换:高-->低:强转
?
//父类(高)--->子类(低):强转;
Person obj=new Student();//低转高,不需要强转
?
//obj将这个对象转换为Student类型,就可以使用Student的方法了
// obj.go();
?
Student obj1=(Student)obj;
obj1.go();//((Student)obj).go();
?
System.out.println("---------------------------------");
?
Student student=new Student();
student.go();
//低类型-->高类型,自动转换
//子类转换为父类:可能会丢失自己原来的方法
Person person=student;
//person.go();//丢失go()方法
?
}
?
}
?