面向对象13:instanceof和类型转换

instance of:
判断一个对象与另一对象是否有父子关系
instanceof 是一个比较转化的过程,如果两边有关系返回true,如果没有关系返回false和编译器报错
(类型转换) 引用类型
instance of例子如下
package com.oop.Demo06;
public class Application3 {
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是否有父子关系
//obj 可以看成object
//看对象和类型是否有父子关系
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 obj3 = new Student();
System.out.println(obj3 instanceof Object);
System.out.println(obj3 instanceof Student); //true
System.out.println(obj3 instanceof Person); //true
// System.out.println(stu instanceof Teacher); //编译报错
// System.out.println(obj3 instanceof String); //编译报错
}
}
输出:
true
true
false
false
=========================
true
true
false
============================
true
true
进程已结束,退出代码 0
类型转换
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转型;强制转换
4.方便方法的调用,减少重复的代码
代码:
package com.oop.Demo06;
public class Application3 {
public static void main(String[] args) {
// 类型之间的转换 :父 子
//高 低
Person obj3 = new Student();
//student 将这个对象转换为Student类型,我们就可以使用Student类型的方法!
//1.和2.等价
//1.
// Student aaa = (Student) obj3; //类型转换,新引入一个变量aaa
// aaa.eat
((Student)obj3).eat(); //2.
//子类转换父类,可能丢失自己本来的一些方法!
Student s1 = new Student();
s1.foot();
s1.eat();
Person person=s1;
person.foot();
// person.eat; //报红
}
}
/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型
3.把父类转换为子类,向下转型;强制转换
4.方便方法的调用,减少重复的代码
*/


浙公网安备 33010602011771号