一、先看问题
question:输出的结果是什么?
package cn.wxy.extendsion;
/**
* 父类
* @author reliveIT
*/
public class Father {
}
package cn.wxy.extendsion;
/**
* 子类
* @author reliveIT
*/
public class Son extends Father{
public void show(){
System.out.println(super.getClass());
}
}
package cn.wxy.extendsion;
/**
* 测试代码
* @author reliveIT
*
*/
public class TestDemo {
public static void main(String[] args) {
Son son = new Son();
son.show();
}
}
正解:class cn.wxy.extendsion.Son
二、或是解答
JKD api文档中关于Object getClass()方法的描述如下:
getClass
public final Class> getClass()返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。
实际结果类型是 Class extends |X|>,其中 |X| 表示清除表达式中的静态类型,该表达式调用 getClass。 例如,以下代码片段中不需要强制转换:
Number n = 0;
Class extends Number> c = n.getClass();
返回:
表示此对象运行时类的 Class 对象。
另请参见:
The Java Language Specification, Third Edition (15.8.2 Class Literals)源码中关于getClass()方法的code如下:
/**
* 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.
*
*
The actual result type is {@code Class extends |X|>}
* where {@code |X|} is the erasure of the static type of the
* expression on which {@code getClass} is called. For
* example, no cast is required in this code fragment:
*
*
* {@code Number n = 0; }
* {@code Class extends Number> c = n.getClass(); }
*
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @see Class Literals, section 15.8.2 of
* The Java™ Language Specification.
*/
public final native Class> getClass();
结论:getClass方法final修饰,因此不能被重写,因此无论是谁调用都调用了Object中final/native的该方法,根据描述(看不到具体的实现代码),getClass方法返回当前的运行时对象的class(字节码对象,即Class的实例对象),因此无论用super还是this修饰,返回的都是当前运行时对象的class。
附注:
如有错漏,烦请指正,不胜感激!