instanceof和类型转换之谜

public class ColorPoint{
	public static void main(String[] args){
		String s = null;
		System.out.println(s instanceof String);
		ColorPoint cp = (ColorPoint) new Object();
	}
}

输出什么?能够编译通过吗

调试发现,可以javac过去,但是java时会输出false,然后抛出异常。

public class ColorPoint{
	public static void main(String[] args){
		System.out.println(new ColorPoint() instanceof String);
	}
}

输出什么?可以编译过去吗?

尝试发现,编译不过去。

import java.util.*;
public class ColorPoint{
<span style="white-space:pre">	</span>public static void main(String[] args){
<span style="white-space:pre">		</span>ColorPoint cp = (ColorPoint) new Point();
<span style="white-space:pre">	</span>}
}
class Point{
}

能编译过去吗?编译不过去。

关于instanceof的几个要求

1、当instanceof做操作数为null时,返回值为false,

2、如果两个操作数都是类,其中一个必须是另一个的子类型

关于类型转换的问题

和instanceof一样,当两个都是类的时候那么其中一个必须是另一个的子类,否则将编译不过去,至于能不能转换,就是运行期的事了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值