JavaSE instanceof与类型转换

instanceof

引用类型,判断一个对象是什么类型

package oop01.demo02;

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

        //System.out.println(x instanceof Y);
        /*
        是否存在父子关系 是否是指向的类型
         */
        //Object--String
        //Object -- person02 -- Student01
        //Object -- person02 -- Teacher

        Object object = new Student01();
        System.out.println(object instanceof Student01);
        System.out.println(object instanceof Person02);
        System.out.println(object instanceof Object);
        System.out.println(object instanceof Teacher);
        System.out.println(object instanceof String);

        System.out.println("======================");
        Person02 person = new Student01();
        System.out.println(person instanceof Student01);
        System.out.println(person instanceof Person02);
        System.out.println(person instanceof Object);
        System.out.println(person instanceof Teacher);
        //System.out.println(person instanceof String);


        System.out.println("======================");
        Student01 student01 = new Student01();
        System.out.println(student01 instanceof Student01);
        System.out.println(student01 instanceof Person02);
        System.out.println(student01 instanceof Object);
        //System.out.println(student01 instanceof Teacher);

    }
}

true
true
true
false  //
false
======================
true
true
true
false
======================
true
true
true

Process finished with exit code 0

类型转换

把父类转换为子类,向下转型;强制转换
(Son(father)).go();
go方法是Son中具有而Father中不具有的

package oop01.demo02;

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

package oop01.demo02;

public class Student01 extends Person02{
    public void go(){
        System.out.println("go");

    }

}

package oop01.demo02;

public class Teacher extends Person02{
}

package oop01.demo02;

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

        //高                     低
        Person02 obj = new Student01();

        ((Student01)obj).go();//父类 -- 子类 向下转型 强制转换

    }
}
//方法的调用 减少重复的代码

把子类转换为父类,向上转型
可能丢失自己本来的一些方法。

Student01 student01 = new Student01();
        student01.go();
        Person02 person02 = student01;
        person02.go();//无法执行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值