instanceof和类型转换

instanceof是Java的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean的数据类型。是,则返回true,否则返false。(可以理解为:判断两个类之间是否有父子关系 ,有父子关系,则返回true,否则返false。 )

判断System.out.println(X instanceof Y);能否通过,看X和Y是否存在父子(血缘关系)。

案例一

public class Application {
    public static void main(String[] args) {
        //Object>Person>Student
        //Object>Person>Teacher
        //Object>String
        //Object是最高级别类(祖宗类)
        Object object = new Student();
        System.out.println(object instanceof Student);
        System.out.println(object instanceof Person);
        System.out.println(object instanceof Object);
        System.out.println(object instanceof Teacher);
        //Teacher是Person下面另一条线和Student无关
        System.out.println(object instanceof String);
        //String是object下面另一条线和Student无关
        System.out.println("=====================");
        Person person = new Student();
        System.out.println(person instanceof Student);
        System.out.println(person instanceof Person);
        System.out.println(person instanceof Object);
        System.out.println(person instanceof Teacher);
        //System.out.println(person instanceof String);
        // person和String是两条完全不相关的线,不能比较,会报错
        System.out.println("=====================");
        Student student = new Student();
        System.out.println(student instanceof Student);
        System.out.println(student instanceof Person);
        System.out.println(student instanceof Object);
        //System.out.println(student instanceof Teacher);
        //student和Teacher是同级不能比较,且是两条不同的线,否则会报错。
        //System.out.println(student instanceof String);
        //Teacher和String是两条完全不相关的线,不能比较,否则会报错。
    }
}
class Person{
}
class Student extends Person{
}
class Teacher extends Person{
}

运行结果:

 案例二

public class Application {
    public static void main(String[] args) {
        //类型之间的转换:父---->子(高-->低)
        //Person>Student
        Person a = new Student();
        //student将这个对象(person类型的)转换为Student类型,就可以使用Student类型的方法了
        ((Student)a).go();
    }
}
class Person{
   
}
class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}

运行结果:go

案例三:错误代码(案例)

public class Application {
    public static void main(String[] args) {
        //类型之间的转换:父---->子(高-->低)
        //子类转父类可能丢失自己本来的一些方法
        Student student = new Student();
        student.go();
        Person person = student;
        person .go();//这里会报错,person 走不了go方法
    }
}
class Person{

}
class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}

总结:

  • 父类的引用指向子类的对象

  • 把子类转换为父类,向上转型

  • 把父类转换为子类,向下转型需要强制转换

猜你喜欢

转载自blog.csdn.net/m0_52896041/article/details/127357641