java上转型之instanceof--避免引用类型强制转化出错

 

Object obj="hello";

 上面的obj是什么类型?

object?NO!String?NO?

答案:编译阶段是Object类型,而在运行阶段是String类型。实际上obj是String类型。只不过分为编译和运行两个部分!

那为什么会发生这种情况呢?

我们知道:对于Object obj而言,程序声明了一个Object类型的变量!

               而“hello”是一个String类型的对象

               将Object类型的变量只想String类型的对象,由上篇可以看出这是一个上转型类型!变量由String类型转到Object类型!

由上转型的知识我们知道,在运行期间,对象是直接调用子类String中的方法(但是变量仍然是调用父类中的变量)

 我们必须清楚这种引用类型的强制类型转化是非常危险的

如: Object obj="hello";  Integer in=obj;

这也就引出了如何避免强制引用类型转化的问题:在java中我们用instanceof 来判断一个引用类型是否可以转化到其他类型

instanceof 用于判断某个对象是否是一个类或则子类,实现类,接口的实例,如果是 则返回true,如何不是则返回false

例子:

	public static void main(String[] args) {
		// TODO Auto-generated method stubs
		Object hello="hello";
		//hello运行时就是String类型:true
		System.out.println((hello instanceof String));
		//hello运行时String类型,而String类型是Object类型的子类,子类上转型:true
		System.out.println((hello instanceof Object));
		//String 类型和Math类型风马牛不相及:false
		System.out.println((hello instanceof Math));
		//String 类型也是Comparable类型的子类:true
		System.out.println((hello instanceof Comparable));
		
		//Integet是Object的子类
		Integer inte=new Integer(7);
		System.out.println(inte instanceof Object);
		
		//不能下转型:false
		Object object=new Object();
		System.out.println("object is Integer:"+(object instanceof Integer));
		
		Integer k=10;
		if((k instanceof Object))
		{
			object=k;  //可以执行,因为k就是一个Integer类型,而Integer类型是Object类型的一个子类,符合上转型
		}
		//通Object o="sf";
		Object o=7;
		System.out.println(o instanceof Integer);
		
	}

 

 

 

 

posted @ 2013-12-12 22:48  Jackvin  阅读(3954)  评论(0编辑  收藏  举报