Java: recursion inside the main class calls a subclass method instead of a native method

Example:

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

Now the problem is this:

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

This is a very strange behavior and problems are programmed! I tried calling recursion with this.doIt (), but that didn't help. Does anyone have an idea?

Thanks for the answers, this problem is resolved.

+7
java recursion subclass
source share
2 answers

The fact that the intended behavior, without setting the final method, means that it can be override n, so you should always consider that someone can do this. A call to this method is never guaranteed for a method at this level.

You can solve this problem elegantly using the ( 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 that the method cannot be overridden. So, at that moment you have a contract (guarantee) that the innerDoIt method innerDoIt indeed the innerDoIt method, which, in your opinion, is.

Thus, in the case you do not want the caller to stop , just hedge it into another final method. By making it protected , this method can also be called using SubClass .

+7
source share
 public class Main { public static void main(String[] args) { B b = new B(); b.doIt(); System.out.println(); A a = new B(); a.doIt(); } public static class A{ boolean check=false; public void doIt(){ System.out.println("A start"); if(check){ } else{ check = true; doIt(); } System.out.println("A end"); } } public static class B extends A{ @Override public void doIt() { System.out.println("B start"); super.doIt(); System.out.println("B end"); } } } 

In this example, both b and a are instances of class b , so, as you probably expect, a.doIt () and b.doIt () will produce the same result.

 B start A start B start A start A end B end A end B end B start A start B start A start A end B end A end B end 

When you call doIt() , you implicitly call this.doIt() , and this is an instance of class b . There is no syntax to do what you want without sharing the contents of doIt() (see CommuSoft answer)

+1
source share

All Articles