super.getClass()与this.getClass() 的区别

来源:互联网 发布:曹查理 知乎 编辑:程序博客网 时间:2024/06/10 00:21

原文地址:http://blog.csdn.net/speedme/article/details/41145143

首先看一段代码:

[java] view plain copy
 print?
  1. import java.util.Date;  
  2. public  class Test extends Date{  
  3.     public static void main(String[] args) {  
  4.         new Test().test();  
  5.     }  
  6.     public void test(){  
  7.         System.out.println(super.getClass().getName());  
  8.     }  
  9. }  


上面这段代码的输出为:Test

可能你会奇怪为什么输出的是Test,而不是Date呢?我明明是调用的super.getClass()啊。我们先不急,先来了解一下getClass()方法的机制是什么。下面时getClass()在Object类中实现的源码。

Returns the runtime classof 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: Number n = 0; Class<? extends Number> c = n.getClass(); Returns: The Class object that represents the runtime class of this object.

public final native Class<?> More ...getClass();

从上面我们可以得知两点:

  1. getClass()方法: 返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。
  2. getClass()时final方法,子类无法重写。

第一点我们可以得出:

什么是运行时类,运行时类是Object的一个实例,注意了,关键来了,他返回的不是Object.class,他返回的是运行时类,就是虚拟机中是谁在运行就是谁,如果你new Date(),Date当然是运行时类,而不是Object,否则所有类的getClass()方法都返回了Object.class 了。

根据上一段解释,Date是Object的子类,Date.getClass()返回的肯定是Date.class,

同样的Test继承Date,假如有一个属于Date的getClass()他返回的也不可能是Date.class,因为当new Test()后,Test是一个运行时类,只不过他拥有Date的资源结构。所以谁被实例化,谁就是一个运行时类。

第二点我们可以得出

上面我们讨论了,Object中getClass()方法返回的是运行时类对象,谁被实例化,getClass()就得到谁。但那只是Object中的getClass()方法而已,而我们时调用的Date.getClass(),or Test.getClass().

这里就涉及到getClass()方法在Object中时final方法了,因此子类是无法重写getClass方法的,所以不管是Date.getClass()还是Test.getClass(),其实调用的都是Object中的getClass()方法,这样就保证了会遵循第一点。

如果想要从Test中得到Date.class,可以用Test.getClass().getSuperClass();


原创粉丝点击