Day23instanceof和类型转换

instanceof是用于new关键词语句中,左侧的对象引用是否为右侧类的实例,放回值为ture或false常配合强制转换使用
而强制转换是父类向子类的转换,子类向父类的转换是自动转换
需要注意的是,在子类向父类的转换过程中,可能会丢失子类本身有的一些方法

package oop1.Demo6;

public class Applicaation2 {
    public static void main(String[] args) {
        //类型之间的转换,高转低,强制转换,低转高,自动转换
        //高                     低
        //低转高自动转换,但子类转换为父类之后,可能会丢失自己的方法
        Person obj =  new Student();
        Student student = (Student) obj;
        student.go();
        //另外一种写法
        ((Student) obj).go();//快捷键:Ctrl+Alt+V可以输出(Student)obj之后直接转成该行代码的形式
    }
}
package oop1.Demo6;

public class Application {
    public static void main(String[] args) {
        //Object > String
        //Object >Person >Teacher
        //Object >Person >Student
        Object o = new Student();
        System.out.println(o instanceof Student);//true
        System.out.println(o instanceof Person);//true
        System.out.println(o instanceof Teacher);//false
        System.out.println(o instanceof Object);//true
        System.out.println(o instanceof String);//false
        System.out.println("========================================");
        Person p = new Student();
        System.out.println(p instanceof Person);//true
        System.out.println(p instanceof Student);//true
        System.out.println(p instanceof Object);//true
        System.out.println(p instanceof Teacher);//false
        //System.out.println(p instanceof String);//编译报错
        System.out.println("=========================================");
        Student s = new Student();
        System.out.println(s instanceof Student);//ture
        System.out.println(s instanceof Person);//ture
        //System.out.println(s instanceof Teacher);//编译报错
        System.out.println(s instanceof Object);//ture
        //System.out.println(s instanceof Teacher);//编译报错
        //ystem.out.println(s instanceof String);//编译报错

        /*
        小结:new关键词左边的部分,决定了instanceof运行时是否能够通过编译,即左边与右边的类是否有继承关系,有则通过
        右边则决定了输出的结果是ture还是false
        而输出的结果为什么取决于new出来的类往上追朔直到Object所途径的类与instanceof左边的实例所在的类对比是否在途径的类当中
        如果是,则是ture,否则false
         */
    }
}
package oop1.Demo6;

public class Person {
    public void run(){
        System.out.println("run");
    }
}
package oop1.Demo6;

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

}
package oop1.Demo6;

public class Teacher extends Person {
}
posted @ 2025-09-28 15:19  冰涿  阅读(17)  评论(0)    收藏  举报