class T2 extens T1{....}___________________________________package lab;public class TMain { public static void main(String[] args) {
         T2 t2=new T2();
         T1 t1=(T1)t2;
         System.out.println(" t1.class:"+t1.getClass());
       }
}
结果显示 t1.class:class lab.T2我想知道,如何令到显示的结果变为  t1.class:class lab.T1 呢?  

解决方案 »

  1.   

    getClass
    public final Class<?> getClass()
    Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. 
    The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:
    搂主没有写,T2 应该是T1的子类吧,不然编译会抱错。
    大概意思就是getclass()返回的是调用这个方法的类实例的 static type,静态类型,所以即使你通过强制类型转换应该还是T2类吧。
      

  2.   


     T1 t1=new T2();  
     System.out.println(" t1.class:"+t1.getClass()); 
      

  3.   

    不好意思看错了,T1 t1=new T2();
    System.out.println(" t1.class:"+t1.getClass().getSuperclass());
      

  4.   

    楼主啊,给你个参考噢,你没有理解程序的内存机制,我给你个设计模式代码,呵呵。因为你的T1,T2其实指向的同一个地址,如果你改变T2的一个变量,那个T1的变量也会跟着变的,其实他们用的同一块地址,呵呵。下面我给你个解决方案。
    public static void main(String[] args) { 
             T2 t2=new T2(); 
             T1 t1=t2.clone(); 
             System.out.println(" t1.class:"+t1.getClass()); 
           } 
    } T2代码:
    public class T  implements Cloneable{

    public Object clone()
       {
            try {
    return super.clone();
    } catch (CloneNotSupportedException e) {
    e.printStackTrace();
    }
    return null;
       }}
    用PROTOTYPE模式,这个问题很简单的解决。