考虑java中的以下代码:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
这是一个名为Subclass的子类,它覆盖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();
}
}
获得的输出如下:
Printed in Superclass
Printed in Subclass
如果子类覆盖超级为什么超类println
仍在屏幕上显示?
不仅仅假设在子类上显示方法的内容?
如果方法重写,为什么在下面的代码中没有调用super?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
答案 0 :(得分:2)
1 由于方法super.printMethod();
2 因为没有调用super
方法。
答案 1 :(得分:2)
如果子类覆盖为什么超类println仍然显示在屏幕上?
因为您致电super.printMethod()
。这会调用printMethod()
的父类实现。
如果方法重写,为什么在以下代码中没有调用super?
因为开发人员不需要或者不希望父类中的代码执行 - 他想完全重写该方法。您可能还会看到未定义父实现时使用的override
关键字,例如使用接口或抽象类。
不需要调用方法的父类实现。
答案 2 :(得分:1)
如果子类覆盖了为什么超类println仍然存在 在屏幕上显示?它不仅仅是为了显示内容 子类上的方法?
这一行:
super.printMethod();
将致电super
班级printMethod()
。这基本上会变成:
new Superclass().printmethod();
您无需调用super来执行覆盖。这样做:
// overrides printMethod in Superclass
public void printMethod() {
//super.printMethod();
System.out.println("Printed in Subclass");
}
解决问题的另一种方法是执行以下操作:
public class Superclass {
public void printMethod() {
System.out.println("Printed in " + this.getClass().getName() + ".");
}
}
然后就这样做:
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();//just do override
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
另一个问题,为什么超级不在以下代码中被调用 如果方法重写?
如上所述,您不需要super
来@Override
。来自this question:
每次覆盖方法时都使用它以获得两个好处。这样做 您可以利用编译器检查来确保您 当你认为自己是一个方法时,实际上是重写方法。这样,如果 你犯了一个错误拼写方法名称的常见错误 正确匹配参数,您将被警告您的方法 实际上并没有像你想象的那样覆盖。其次,它使 您的代码更容易理解,因为它在方法时更明显 被覆盖。
此外,在Java 1.6中,您可以使用它来标记方法 实现一个具有相同优点的接口。我想是的 最好有一个单独的注释(如@Implements),但它是 总而言之。
如果您想了解更多关于何时使用{{1>} 方法覆盖 ,那么check this article question.
答案 3 :(得分:0)
您不必使用super.printMethod();
调用超类方法来覆盖该方法,但是您这样做了,所以
Printed in Superclass
已打印。要不打印,请取消对super.printMethod();
的调用;没必要。
对于onCreateOptionsMenu
,它没有使用重写的功能,因此无需拨打super.onCreateOptionsMenu
。
答案 4 :(得分:0)
调用super()时,调用超类方法。如果你只是删除了super()调用,那么在没有“Printed in Superclass”打印的情况下仍然可以使用覆盖。