instanceof 的使用
instanceof 引用类型,用于判断一个对象是什么类型
可以用来判断两个类之间是否存在父子关系
//Object >> Person >> student
//Object >> String
//instance of 两边的类必须存在父子关系,如果没有父子关系,编译不会通过
// X instanceof Y
/*编译是否通过的因素在于,X与Y是否有父子关系*/
/*当X是Y的父类时,返回true*/
/*当X是Y的子类时,返回false*/
public static void main(String[] args) {
Object object = new Demo01.Student();
Demo01.Person person = new Demo01.Student();
System.out.println(object instanceof Demo01.Student);//true
System.out.println(object instanceof Demo01.Person);//true
System.out.println(object instanceof String);//false
System.out.println("=====================================");
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
X instanceof Y
编译是否通过的因素在于,X与Y是否有父子关系
当X是Y的父类时,返回true
当X是Y的子类时,返回false
强制类型转换
public static void main(String[] args) {
//类型之间的强制转换:父 子
//等级: 高 低
Person obj = new Student();
/*obj.go(); 由于直接进行类型转换,Person类中并没有go方法,因此编译不过*/
//obj将这个对象(此时为Person类型)转换成Student类型,就能使用Student类中的方法了
Student student = (Student) obj;/*通过这种方法就可以将obj强制转换*/
((Student)obj).go();/*通过这种方式直接对obj对象进行类型的强制转换并使用*/
//子类转换成父类,可能会丢失一部分方法
}
要点:
1.父类的引用指向子类的对象*
2.子类对象转换成父类(向上转型),直接转换*
3.父类对象转换成子类,强制转换*
4.强制转换可能会使子类丢失一部分方法