java面向对象18_instanceof运算符

本文详细介绍了Java中instanceof运算符的用法,包括其在运行时和编译时的特点。instanceof用于判断对象是否是特定类或接口的实例,避免在向下转型时出现ClassCastException。内容涵盖instanceof的语法、注意事项以及编译和运行时的行为,并通过示例进行说明。

1.instanceof运算符

当要使用子类特有功能时,就需要使用向下转型。但是面对具体的子类对象,在向下转型时容易发生ClassCastException类型转换异常,在转换之前必须做类型判断。

java中的instanceof运算符,用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。

语法格式:boolean result = object instanceof class

注意事项:

  1. obj可以是一个对象,也可以为null。

  2. class可以是一个类(class),也可以是接口(interface)。

  3. instanceof二元运算符返回的结果是boolean类型。

2.instanceof编译时特点

  • 当obj为null的时候:

    当obj为null的时候,instanceof的右侧可以是任意类或接口。

  • 当obj不为null的时候:
    当右边类或接口是左边对象的父类、本身类和子类时,编译通过。
    本身类:指的就是“编译时类型”。

【示例】instanceof编译时的特点演示

class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}
class SmallDog extends Dog {}
public class Test01 {
	public static void main(String[] args) {
		// System.out.println(null instanceof Math); // 编译通过
		// 编译时类型	 运行时类型
		Animal animal = new Dog();
		// 编译时:本身类的父类		
		System.out.println(animal instanceof Object); // 编译通过
		// 编译时:本身类			
		System.out.println(animal instanceof Animal); // 编译通过
		// 编译时:本身类子类			
		System.out.println(animal instanceof Cat);  // 编译通过
		// 编译时:本身类子类			
		System.out.println(animal instanceof Dog); // 编译通过
		// 编译时:本身类子类			
		System.out.println(animal instanceof SmallDog); // 编译通过
		// 编译时:和本身类没有任何联系
		// boolean flag5 = animal instanceof String; // 编译失败
	}
}

2.instanceof运行时特点

  • 当obj为null的时候:
    instanceof运算的结果永远为false。
  • 当obj不为null的时候:
    当右边类或接口是左边对象的父类、本身类时,instanceof运算的结果是true。
    当右边类或接口是左边对象的兄弟类、子类时,instanceof运算的结果是false。
    本身类:指的就是“运行时类型”。

【示例】instanceof运行时特点演示

class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}
class SmallDog extends Dog {}
public class Test01 {
	public static void main(String[] args) {
		// System.out.println(null instanceof Math); // false
		// 编译时类型	 运行时类型
		Animal animal = new Dog();
		// 运行时:本身类的父类
		System.out.println(animal instanceof Object); // true
		// 运行时:本身类的父类
		System.out.println(animal instanceof Animal); // true
		// 运行时:本身类的兄弟类
		System.out.println(animal instanceof Cat);  // false
		// 运行时:本身类
		System.out.println(animal instanceof Dog); // true
		// 运行时:本身类的子类
		System.out.println(animal instanceof SmallDog); // false
	}
}

ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值