第七章 课堂例子 怎样判断对象是否可以转换?

怎样判断对象是否可以转换?

可以使用instanceof运算符判断一个对象是否可以转换为指定的类型:

        Object obj="Hello";

if(obj instanceof String)

      System.out.println("obj对象可以被转换为字符串");

public class ka
{
	public static void main(String[] args) 
	{
		//声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
		//但hello变量的实际类型是String
		Object hello = "Hello";
		//String是Object类的子类,所以返回true。
		System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
		//返回true。
		System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
		//返回false。
		System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));
		//String实现了Comparable接口,所以返回true。
		System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));
		String a = "Hello";
		//String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
		//System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
	}
}

  

行结果:

字符串是否是Object类的实例:true

字符串是否是String类的实例:true

字符串是否是Math类的实例:false

字符串是否是Comparable接口的实例:true

运行截图:1

2

实验原理:

声明hello时使用Object类,则hello的编译类型是ObjectObject是所有类的父类,但是hello变量的实际类型是StringStringObject类的子类,所以返回true(已经转换了)。

1、这行代码System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));返回true(已经转换了)。

2、不过这行代码System.out.println("字符串是否是String类的实例:" + (hello instanceof String));没有转换:

3、/String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过 //System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));

原文地址:https://www.cnblogs.com/hanzhu/p/4959895.html