javarecursionsubclassmainclass

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:

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.


Solution

  • 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.