instanceof判断实例的类型详解

1、instanceof 比较左边的对象所指向的对象是不是右边类的一个实例(这里是使用类C++里的指针,java中没有指针,但是存储在堆栈中的对象的引用指向存储在堆中的对象,类似于C++中的指针)。也就是说左边的对象必须实例化之后,才有可能是右边类的一个实例。如下代码中,由于p并没有进行实例化,而只是一个对象的引用,所以p instanceof Parent 是false。

class Parent {}

public class Instanceof {
	public static void main(String[] args) {
		Parent p = null;
		if(p instanceof Parent) {
			System.out.println("p is the instance of Parent!");
		}else {
			System.out.println("p is not the instance of Parent!");
		}
	}
}
结果:p is not the instance of Parent!

2、任何继承自父类的一个子类的一个实例,都是父类的一个实例。

class Parent {}

class Child1 extends Parent {}

class Child2 extends Child1 {}

public class Instanceof {
	public static void main(String[] args) {
		Child2 child2 = new Child2();
		if(child2 instanceof Parent) {
			System.out.println("child2 is the instance of Parent!");
		}else {
			System.out.println("child2 is not the instance of Parent!");
		}
	}
}
结果:child2 is the instance of Parent!
3、父类的实例,不是子类的一个实例。

class Parent {}

class Child1 extends Parent {}

public class Instanceof {
	public static void main(String[] args) {
		Parent parent = new Parent();
		if(parent instanceof Child1) {
			System.out.println("parent is the instance of Child1!");
		}else {
			System.out.println("parent is not the instance of Child1!");
		}
	}
}
结果:parent is not the instance of Child1!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值