getClass方法

下面程序的输出结果是多少?
import java.util.Date;
public  class Test extends Date{
public static void main(String[] args) {
new Test().test();
}

public void test(){
System.out.println(super.getClass().getName());
}
}

很奇怪,结果是Test

第一:不管是T1的getClass()还是Date的getClass(),他们都是非覆盖式的从Object继承来的。


第二: Object的getClass()方法的释义是: 返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。

    /**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     **/

     释义指出,要返回此Object运行时类,这外当然不可能指Object自己了,否则所有类调用getClass()方法都返回Object.class了。

    那到底谁是Object的运行时类呢,不是Object自己,当然就只能是他的儿子、或各种孙子了,到底是谁呢,举个例子:
    Date作为直接继承Object的类,作为Object的儿子,如果调用Date.getClass(),返回的是什么呢?在Date中,无论是this.getClass()还是super.getClass(),毫无疑问都指向了Object.getClass()。根据上一段解释,Object.getClass()返回不可能是Object.class,那没得说,只能是Date.class了。

     根据上段: new Date()时,Date是Object的运行时类。

     同理: 根据LZ的例子,new T1()时,运行是类不可能是T1他老子Date,更不会他各种老老子(如Object),只能是自己。

    再回到Object.getClass()释义,返回的只能是T1.class

第三:如果想要从T1中得到Date.class,可以用T1.getClass().getSuperClass();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值