instanceof 和类型转换

2023-12-13 23:28:50
/**
 * @Description instanceof 和类型转换
 */
package com.oop;

import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.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(X instanceof Y);//能不能编译通过!

        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
        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);   //编译报错

        //类型之间的转化:  父   子

        //高                    低
        Person obj = new Student();

        //student将这个对象转换为Student类型,我们就可以使用Student类型的方法了

        /**
         *      Student student1 = (Student) obj;
         *      student1.go();
         */
        ((Student) obj).go();

        //子类转换为父类,可能丢失自己的本来的一些方法!
        Student student2 = new Student();
        student2.go();
        //低                   高
        Person person1 = student2;

    }

}
    /*
    选中下一个相同内容的快捷键是:Alt + J
    选中所有相同内容的快捷键是:Ctrl + Shift + Alt + J
     */

    /*
        1.父类引用指向子类的对象
        2.把子类转换为父类,向上转型;
        3.把父类转换为子类,向上转型; 强制转换
        4.方便方法的调用,减少重复的代码!简介

        封装、继承、多态!   抽象类,接口

     */
/**
 * @Description instanceof和类型转换
 */
package com.oop.demo06;

public class Person {

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

}

/**
 * @Description instanceof和类型转换
 */
package com.oop.demo06;

public class Teacher extends Person{

}

/**
 * @Description instanceof和类型转换
 */
package com.oop.demo06;

public class Student extends Person{

    public void go(){
        System.out.println("go");
    }

}

文章来源:https://blog.csdn.net/my_lucky_bird/article/details/134982488
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。