首先看一段代码:
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
可能你会奇怪为什么输出的是Test,而不是Date呢?我明明是调用的super.getClass()啊。我们先不急,先来了解一下getClass()方法的机制是什么。以下时getClass()在Object类中实现的源代码。
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: Number n = 0; Class<? extends Number> c = n.getClass(); Returns: The Class object that represents the runtime class of this object. getClass()方法: 返回此 Object 的执行时类。
public final native Class<?> More ...getClass(); getClass()是final方法。子类无法重写。
关键是理解super的含义:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
Using the Keyword super
Accessing Superclass Members
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super
. You can also use super
to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass
:
public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } }
Here is a subclass, called Subclass
, that overrides printMethod()
:
public class Subclass extends Superclass { // overrides printMethod in Superclass public void printMethod() { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } }
Within Subclass
, the simple name printMethod()
refers to the one declared in Subclass
, which overrides the one in Superclass
. So, to refer to printMethod()
inherited from Superclass
, Subclass
must use a qualified name, using super
as shown. Compiling and executing Subclass
prints the following:
Printed in Superclass. Printed in Subclass
使用super来引用 被子类覆盖的父类的方法。跟父类对象没有关系。
用来引用一个方法而已。