instanceof与类型转化

instanceof

java中用来判断两个类是否有无父子关系 (能否编译通过)

创建Person类的两个子类Student类和Teacher类

package com.yuanyu.Oop;

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 Object); //true
        System.out.println(object instanceof Person); //true
        System.out.println(object  instanceof Student); //true
        System.out.println(object  instanceof Teacher); //false
        System.out.println(object  instanceof String); //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); //编译就开始报错
        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);  //编译就开始报错
    }
}


类型之间的转化

package com.yuanyu.Oop;

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

package com.yuanyu.Oop;

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

package com.yuanyu.Oop;

public class Application {
    public static void main(String[] args) {
        //类型转化
        // 低
        //Student student = new Student();
        //高                    低
        Person student = new Student(); //低类型到高类型,自动转化
        //student.go(); //编译报错
        //将student这个对象转化为Student这个类型即可使用Student类中的方法
        // 低
        ((Student) student).go(); //强制转化,此时可使用Student类中的方法
        //Student student1 = (Student) student;
        //student1.go();

    }
}

子类(低)转化为父类(高)是自动转化即父类的引用指向子类的对象,父类(高)转化为子类(低)是强制转化

子类转化为父类可能会丢失一些自己的本来方法

类型转化是为了方便方法的调用,减少重复的代码

posted @ 2022-01-08 09:56  原语  阅读(44)  评论(0)    收藏  举报