2
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?

Keen Sage
  • 1,899
  • 5
  • 26
  • 44
  • 2
    If somebody wrote that kind of code at a place where I work, I would seriously consider finding a different job. I sincerely hope that is an educational exercise. – Greg Hewgill Oct 05 '11 at 18:46
  • 1
    I hope the students won't write such code in the real life projects – Boris Treukhov Oct 05 '11 at 18:48
  • It has nothing to do with homework. :). I just came across this problem and was unable to find a solution to call the overridden method. And I don't think this kind of problem will ever come in a practical scenario. – Keen Sage Oct 05 '11 at 18:52
  • Related http://stackoverflow.com/questions/4836708/calling-base-class-overridden-function-from-base-class-method – Bala R Oct 05 '11 at 18:57
  • 1
    still I don't believe this code can't rewritten from scratch - favor composition over inheritance..favor composition over inheritance..favor composition over inheritance – Boris Treukhov Oct 05 '11 at 19:02

1 Answers1

5

Do something like this:

class Parent{

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

    void m2(){
        m2impl();
    }
}
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186