在 Java 类和对象中,我们使用“this”关键字来引用类中的当前对象。 在某种意义上,我相信“this”实际上返回了它自身的对象。
示例:
class Lion
{
public void Test()
{
System.out.println(this); //prints itself (A Lion object)
}
}
在父类(super class)和子类的场景中。我认为“super”关键字会返回父类(super class)的对象。不过这次我好像听错了:
示例:
class Parent
{
public Parent(){
}
}
class Child extends Parent
{
public Child(){
System.out.println(super.getClass()); //returns Child. Why?
}
}
我的问题:在上面的示例中,我希望编译器打印出 class Parent
,但它却打印出 class Child
。为什么会这样?什么 super 实际返回?
最佳答案
使用 super
的方法调用只会忽略当前类中的任何重写。例如:
class Parent {
@Override public String toString() {
return "Parent";
}
}
class Child extends Parent {
@Override public String toString() {
return "Child";
}
public void callToString() {
System.out.println(toString()); // "Child"
System.out.println(super.toString()); // "Parent"
}
}
在调用 getClass()
的情况下,这是一个返回调用它的类的方法,并且不能被覆盖 - 所以虽然我明白你可能期望的原因它返回 Parent.class
,它仍然使用与正常相同的实现,返回 Child
。 (如果你真的想要父类,你应该看看 Class
API。)
事实上,这通常用作覆盖的一部分。例如:
@Override public void validate() {
// Allow the parent class to validate first...
super.validate();
// ... then perform child-specific validation
if (someChildField == 0) {
throw new SomeValidationException("...");
}
}
关于java - 在 Java 中,super.getClass() 打印 "Child"而不是 "Parent"- 为什么会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002433/