首页 > 其他分享 >引用类型转换

引用类型转换

时间:2022-10-17 21:57:01浏览次数:31  
标签:类型转换 instanceof System Person 引用 Student println out

instanceof

        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
        System.out.println(object instanceof String);  //false

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

        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(person instanceof String);  //编译报错

        Object obj = new Person();
        System.out.println(obj instanceof Student); //FALSE
        System.out.println(obj instanceof Person); //true
        System.out.println(obj instanceof Object); //true
        System.out.println(obj instanceof Teacher); //FALSE
        System.out.println(obj instanceof String);  //FALSE


        Object > Student
        Object > Person > Teacher
        Object > Person > Student
        Object > String
        System.out.println( X instanceof  Y); X与Y没有父子关系编辑报错

package com.huan.oop.demo03;

/**
 * 多态
 * @author huan
 */
public class Person {

    public void say(){
        System.out.println("说了一句话");
    }


}


package com.huan.oop.demo03;

public class Teacher extends Person {
}


package com.huan.oop.demo03;

public class Student extends Person {
  public void read(){
      System.out.println("学生类");
  }
}

类型转换

        //类型之间转换 :父类 、子类
        // 子类转换为父类,可以直接转换,可能丢失自己本来一些方法
        Student student = new Student();
        student.say();
        Person person = student;
        Person p = new Student();
        ((Student) p).read();

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

标签:类型转换,instanceof,System,Person,引用,Student,println,out
From: https://www.cnblogs.com/huanshiz/p/16800849.html

相关文章