Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: recursion within main-class calls subclass-method instead of its own method

Example:

class MainClass {
    public doIt() {
        ...
        else doIt();
    }
}

class SubClass extends MainClass {
    @Override
    public doIt() {
        super.doIt();
        ...
    }
}

Now the problem is:

  • I call SubClass.doIt()
  • MainClass.doIt() is called
  • MainClass.doIt() makes recursion calling doIt()
    But: the SubClass.doIt() is called instead of MainClass.doIt()

That is very strange behaviour and problems are programmed! I tried to call the recursion with this.doIt() but that didn't help. Someone has an idea?

Thanks alot for your answers, this problem is solved.

like image 285
Sneedlewoods Avatar asked Feb 19 '15 18:02

Sneedlewoods


1 Answers

That's the supposed behavior, by not setting a method final, that means it can be overriden, so you must always take into account someone can do this. Call's to that method are never guaranteed to be to the method at that level.

You can however solve this problem elegantly, by using a (protected) final method:

class MainClass {

    protected final void innerDoIt () { //final: so no @Override
        ...
        else innerDoIt();
    }

    public void doIt() {
        innerDoIt();
    }

}

And then:

class SubClass extends MainClass {

    @Override
    public doIt() {
        super.doIt();
        ...
    }
}

final ensures, the method can't be overriden. So at that moment, you have a contract (guarantee) that the innerDoIt method is indeed the innerDoIt method you think it is.

So in case you don't wan't the caller to get overriden, simply hedge it into another final method. By making it protected, that method can also be called by the SubClass.

like image 135
Willem Van Onsem Avatar answered Oct 05 '22 10:10

Willem Van Onsem