`

知识梳理:回顾Java父类,子类问题

 
阅读更多
父类:Class Father
子类:Class Son extends Father

package com.zwq.test;

/**
 * 
 * @author Jerome
 */
public class Father {
	static String father_name = "";
	String father_filed_name="Father";

	static {
		father_name = "I am Father!";
		System.out.println("Father static stock");
	}

	Father() {
		System.out.println("Father Constructor");
	}

}




package com.zwq.test;

/**
 * 
 * @author Jerome
 */
public class Son extends Father {
	static String son_name = "";
	String son_filed_name="Son";

	static {
		son_name = "I am Father!";
		System.out.println("Son static stock");
	}

	Son() {
		System.out.println("Son Constructor");
	}
}



一、执行顺序:
Son son = new Son();

运行结果:
Father static stock
son static stock
Father Constructor
son Constructor

总结:
1、现有父类,再有子类:当要创建子类这个对象时,发现这个类需要一个父类,所以把父类的.class加载进来,先构造父类;
2、创建顺序依次是:静态变量、块、方法-->成员变量、方法;


二、相互转化:
1、子类——>父类:
Father father = new Son();

在这里Son 对象实例被向上转型为Father了,但Son对象实例在内存中的本质还是Son类型的,是只father实例指向了son对象。这个时候其能力临时被消弱了,即:部分属于Son而不属于Father的属性和方法无法使用。

2、父类——>子类:
Son son = (Son)new Father();

属于强制类型转换,上述转换会抛出ClassCastException异常信息,当引用类型的真实身份是父类本身的类型时,强制类型转换就会产生错误。
Father son = new Son();
Son son1 = (Son)son;

这样就可以强制转换了,即要转换成什么类型,其本质应该是什么类型;

三、instanceof:
java中的instanceof运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
直接引用别人的结论:
1、对象实现一个接口,用这个对象和这个接口进行instanceof判断,都为true。
2、对象和父类进行instanceof判断,都为true。
3、对象和他的子类进行instanceof判断为false。
可参看:http://09572.iteye.com/blog/1562277
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics