Java基础(十一):instanceof关键字详解

面向对象

instanceof 关键字

  • 判断两个类之间是否存在父子关系
  • 可以把Object、Person、Student理解成三个包含的大圆,new了一个Student()对象,那么这个对象的实际位置就在Student这个圆里

用 instanceof 进行比较,就是判断对象的实际位置是不是在圆里。

  • instanceof 要求对应的两个类要有包含关系
  • 【看等号的左边,存在继承可判断是否可编译!看等号右边,看实际位置是否存在继承!】
父类
package com.oop.demo06;
public class Person {
    public void run(){
        System.out.println("run");
    }
}
子类
//子类文件1
package com.oop.demo06;
public class Teacher extends Person{
}


//子类文件2
package com.oop.demo06;
public class Student extends Person{
}
运行文件
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 > Student
        //Object > Person > Teacher
        //左边为类;右边为实例!
        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(student instanceof String);不可编译
    }
}
  • 父类向子类转型时,要强制类型转换 ((Student)student).go();强制转换
  • 子类向父类转型时,会丢失子类特有的方法!Person person = student;
运行文件
package com.oop;

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

public class Application {
    public static void main(String[] args) {
        //类型之间的转换:父     子


        //高---------->------------- 低
        Person student = new Student();
        //将student这个对象转换为Student类型,我们就可以使用Student类型的方法了!
        ((Student)student).go();//方法一:强制转换
        Student student1 = (Student) student;//方法二:强制转换
        student1.go();


        //低--------->------------高
        Student student2 = new Student();
        Person person = student2;//自动转换
        person.run();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值