你的位置:首页 > Java教程

[Java教程]引用和对象实例的区别


父类:

package test;public class FatherClass {	protected int i=0;}

  子类:

package test;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Child extends FatherClass {	public int i1=1;	public void function(){		System.out.println("call Child1 function");	}	public static void main(String []args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{		//开始执行main		System.out.println("the entrance.");		System.out.println("----------------");		//父类引用指向子类对象实例		FatherClass f;		f=new Child();				//f.function();//不符合语法规则,编译不通过		System.out.println(f);		System.out.println(f.getClass());		System.out.println("----------------");		//子类引用指向子类对象实例		Child c1;		c1=(Child) f;				c1.function();		System.out.println(c1);		System.out.println(c1.getClass());				//运行时通过Method调用方法		Method m=Child.class.getMethod("function");		m.invoke(f);//输出正常				//子类引用指向了父类实例,父类中并没有void function()		//编译正确但是运行错误		Child c2=(Child) new FatherClass();		m.invoke(c2);//Exception		/**		 * Exception in thread "main" java.lang.ClassCastException: 		 * test.FatherClass cannot be cast to test.Child1	at test.Child1.main(Child1.java:36)		 */	}}

  

输出:

the entrance.
----------------
test.Child@2a139a55
class test.Child
----------------
call Child1 function
test.Child@2a139a55
class test.Child
call Child1 function
Exception in thread "main" java.lang.ClassCastException: test.FatherClass cannot be cast to test.Child
at test.Child.main(Child.java:37)