开发者

How to solve the following issue in java?

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();
    }
}

This Code results in a java.lang.StackOverflowError because when m1() method of the Parent class is invoked, it calls m2() method which is child's m2() method hence results in StackOverflowError.

What should be changed in the Parents m1() method so that it calls Parent's m2() method instead of Child's m2() method?


Do something like this:

class Parent{

    void m1(){
        System.out.println("Parent : m1");
        m2impl();
    }
    private void m2impl() { /* whatever */ }

    void m2(){
        m2impl();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜