instance of
判断一个对象与另一对象是否有父子关系
(类型转换) 引用类型
instance of例子如下
package com.oop.demo08;
public class Application {
public static void main(String[] args) {
//Object > Person > Student
// Object > Person > Teacher
// Object > String
Object obj = new Student();
// System.out.println(X instanceof Y); //能不能编译通过,取决于X和Y是否有父子关系
System.out.println(obj instanceof Student); //true
System.out.println(obj instanceof Person); //true
System.out.println(obj instanceof Teacher); //false
System.out.println(obj instanceof String); //false
System.out.println("=========================");
Person obj2 = new Student();
System.out.println(obj2 instanceof Student); //true
System.out.println(obj2 instanceof Person); //true
System.out.println(obj2 instanceof Teacher); //false
// System.out.println(obj2 instanceof String); //编译报错
System.out.println("============================");
Student stu = new Student();
System.out.println(stu instanceof Student); //true
System.out.println(stu instanceof Person); //true
// System.out.println(stu instanceof Teacher); //编译报错
// System.out.println(stu instanceof String); //编译报错
}
}
类型转换
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转型;强制转换
4.方便方法的调用,减少重复的代码
代码
package com.oop.demo08;
public class Application {
public static void main(String[] args) {
// 类型之间的转换 :父 子
//高 低
Person obj3 = new Student();
//student 将这个对象转换为Student类型,我们就可以使用Student类型的方法!
Student student =(Student)obj3;
student.go();
//子类转换父类,可能丢失自己本来的一些方法!
Student stu1 = new Student();
stu1.go();
Person person = stu1;
// person.go();
}
}
/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转型;强制转换
4.方便方法的调用,减少重复的代码
*/
本文详细解析了Java中instanceof操作符的用途,即判断对象间是否存在父子类关系,以及类型转换的过程,包括向上转型、向下转型和强制转换等,通过实例展示了如何在实际代码中应用这些概念。
377

被折叠的 条评论
为什么被折叠?



