目录
instanceof (类型转换) 引用类型,判断一个对象是什么类型
万能公式:System.out.println(X instanceof Y);
能不能编译通过!取决于X和Y是否是父子关系,X和Y是否有关系,有关系但不是父子关系,编译通过,但是会输出False
Application测试类
package com.demo1.demo09;
import com.demo1.demo09.demo9.Person;
import com.demo1.demo09.demo9.Student;
import com.demo1.demo09.demo9.Teacher;
public class Application {
public static void main(String[] args) {
//三条继承路线
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
//同级但不同线,但Object和Teacher是有关系的,才不会直接报错而是打印False
System.out.println(object instanceof String);//false
//不同路线,且Object和String(是在java包里面的)是有关系的,才不会直接报错而是打印False
System.out.println("分界线===========================================================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//False
// System.out.println(person instanceof String);//编译直接报错 直接就是不同路线且是同级的
//代码的运行分为编译和运行两步,编译的时候只看类型,所以是先去看的instanceof两边的数据类型是否有父子关系
System.out.println("分界线=============================================================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译直接报错 同级不同路线
// System.out.println(student instanceof String);//编译直接报错 直接就是不同路线
}
}
类型转换
Person类
public class Person {
public void run(){
System.out.println("run");
}
}
Student类
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
父类无法直接调用子类中的方法,会报红,需要进行类型转换
类型转换 高转低
public class Application {
public static void main(String[] args) {
//类型之间的转换: 父 子
//高 转 低
Person obj = new Student();
//将这个对象(obj)转换为Student类型,我们就可以使用Student类型的方法了
Student student = (Student)obj;
student.go();
//((Student)obj).go(); 代码缩写
}
}
类型转换 低转高
public class Application {
public static void main(String[] args) {
//子类转换为父类,可能丢失自己本来的一些方法
//低转高 不用强制转换
Student s1 = new Student();
student.go();
Person person=s1;//父类引用指向子类对象
((Student) person).go();//按刚刚来说,是可以不用强转就可以用go方法的,也说明了子类转换为父类,可能丢失自己的本来一些方法
}
}
总结
1.父类引用指向子类对象(前提) 2.把子类转换为父类,向上转型,不用强制转换 3.把父类转换为子类,向下转型,强制转换,可能会丢失方法 4.方便方法的调用,减少重复的代码 简洁 抽象: 封装 继承 多态