关于Java中instanceof关键字的说明

背景

        应用后期特此纪要!

问题

        Java中instanceof关键字的作用是什么?

说明

        instanceof是Java中的一类关键字。

纪要

作用:用来判断内存中实际对象A是不是B类型,一般用来做类的类型判断。

Eg:

        cat、dog继承自animal,tree继承自botany
        cat instanceof animal 返回 true
        dog instanceof cat 返回 false
        cat instanceof botany 返回 false

下面是两个Demo实例,可以运行参考:

package www.demo;

/**
 * Cat
 * @author Administrator
 *
 */
class Cat extends Animal{
	
}

/**
 * Dog
 * @author Administrator
 *
 */
class Dog extends Animal{
	
}

/**
 * Animal
 * @author Administrator
 *
 */
class Animal {
	
}

public class Instanceof_test {

	public static void main(String[] args) {
		/**
		 * 语法: boolean result = obj instanceof Class
		 * 解析:
		 * 		1.obj为实际内存中的对象。Class为类或接口。[当obj为Class的对象,或者是其直接或间接子类,或者是其接口的实现类,都将返回true]
		 * 		2.编译时编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错。
		 * 结论:
		 * 		1.obj必须是引用类型,不能是基本类型。
		 * 		2.obj若为null,不论和什么类型instanceof都将返回false(null用instanceof跟任何类型比较时都是false)。
		 */
		Cat cat = new Cat();
		Dog dog = new Dog();
		System.out.println(cat instanceof Animal); //true 
		System.out.println(dog instanceof Animal); //true 
		
		System.out.println(cat instanceof Cat); //true 
		System.out.println(dog instanceof Dog); //true 
		
//		System.out.println(cat instanceof Dog); // 编译不通过 “Incompatible conditional operand types Cat and Dog”
		
	}
}
package www.demo;


/**
 * Animal
 * @author Administrator
 *
 */
interface Animal {
	
}

/**
 * Cat
 * @author Administrator
 *
 */
class Cat implements Animal{
	
}

/**
 * Dog
 * @author Administrator
 *
 */
class Dog implements Animal{
	
}

public class Instanceof_test {

	public static void main(String[] args) {
		/**
		 * 语法: boolean result = obj instanceof Class
		 * 解析:
		 * 		1.obj为实际内存中的对象。Class为类或接口。[当obj为Class的对象,或者是其直接或间接子类,或者是其接口的实现类,都将返回true]
		 * 		2.编译时编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错。
		 * 结论:
		 * 		1.obj必须是引用类型,不能是基本类型。
		 * 		2.obj若为null,不论和什么类型instanceof都将返回false(null用instanceof跟任何类型比较时都是false)。
		 */
		Cat cat = new Cat();
		Dog dog = new Dog();
		System.out.println(cat instanceof Animal); //true 
		System.out.println(dog instanceof Animal); //true 
		
		System.out.println(cat instanceof Cat); //true 
		System.out.println(dog instanceof Dog); //true 
		
//		System.out.println(cat instanceof Dog); // 编译不通过 “Incompatible conditional operand types Cat and Dog”
		
	}
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值