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();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码导致java.lang.StackOverflowError,因为当调用Parent类的m1()方法时,它调用m2()方法,这是child的m2()方法,因此导致StackOverflowError.
什么应该在Parents m1()方法中更改,以便它调用Parent的m2()方法而不是Child的m2()方法?
做这样的事情:
class Parent{
void m1(){
System.out.println("Parent : m1");
m2impl();
}
private void m2impl() { /* whatever */ }
void m2(){
m2impl();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |