public class Example {
public static void main(String args[]){
Parent p = new Child();
p.m2();
}
}
class Parent{
void m1(){
System.out.println("Parent : m1");
m2();
}
void m2(){
System.out.println("Parent : m2");
}
}
class Child extends Parent{
void m1(){
super.m1();
System.out.println("Child : m1");
}
void m2(){
System.out.println("Child : m2");
m1();
}
}
此代碼導致java.lang.StackOverflowError,因爲當調用Parent類的m1()方法時,它會調用m2()方法,這是child的m2()方法,因此會導致StackOverflowError。如何在java中解決以下問題?
父母m1()方法應該改變什麼,以便它調用Parent的m2()方法而不是Child的m2()方法?
這是功課? – Bernard
如果有人在我工作的地方寫這種代碼,我會認真考慮找一份不同的工作。我衷心希望這是一項教育活動。 –
我希望學生不要在現實生活中寫這樣的代碼 –