一、先看问题
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.
*
* <p><b>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.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @see Class Literals, section 15.8.2 of
* <cite>The Java™ Language Specification</cite>.
*/
public final native Class<?> getClass();
附注:
如有错漏,烦请指正,不胜感激!