instanceof和类型转换

本文探讨了Java中的instanceof关键字,如何用于判断对象类型,并介绍了子类自动转型为父类和父类强制转型为子类的区别,以及在不同场景下的类型转换及其可能带来的方法丢失问题。通过实例演示了Object到Person再到具体类的转换过程。
摘要由CSDN通过智能技术生成

instanceof(类型转换)引用类型,判断一个对象是什么类型

​ 在继承中,子类可以自动转型为父类,但是父类强制转换为子类时只有当引用类型真正的身份为子类时才会强制转换成功,否则失败

  1. 父类引用指向子类的对象
  2. 把子类转换为父类,向上转型:自动转换,丢失子类中原本可直接调用的特有方法
  3. 把父类转换为子类,向下转型:强制转换 ,会丢失父类被子类所重写掉的方法
  4. 方便方法的使用,减少重复的代码!简洁
package com.oop;

import com.oop.demo06.Student;
import com.oop.demo06.Person;
import com.oop.demo06.Teacher;

public class Application {
    public static void main(String[] args) {


        //Object>Person>Student
        //Object>Person>Teacher
        //Object>String
        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

        System.out.println("====================================");

        Teacher teacher = new Teacher();
        //System.out.println(teacher instanceof Student); 编译出错
        System.out.println(teacher instanceof Person);//true
        System.out.println(teacher instanceof Object);//true
        System.out.println(teacher instanceof Teacher);//true
        //System.out.println(teacher instanceof String);编译出错

        System.out.println("====================================");

        String string = new String();
        //System.out.println(string instanceof Student);编译出错
        //System.out.println(string instanceof Person);编译出错
        System.out.println(string instanceof Object);//true
        //System.out.println(string instanceof Teacher);编译出错
        System.out.println(string instanceof String);//true
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tGGks4xr-1619054747929)(C:\Users\Admin\AppData\Roaming\Typora\typora-user-images\1618902863947.png)]

package com.oop;

import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.Person;

public class Application {
    public static void main(String[] args) {

        //类型之间的转换:基本类型自动转换
        //高                  低
        Person obj = new Student();
        //student将这个转换为Student类型,我们就可以使用Student类型的方法了
        ((Student)obj).go();

        Student student=new Student();
        student.run();
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KR1OaLzL-1619054747935)(C:\Users\Admin\AppData\Roaming\Typora\typora-user-images\1618905040705.png)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值