mekazu
mekazu

Reputation: 2705

In Java can you call a public overridden method from a different class?

Typically an overridden method can be called with super. For example:

public class SuperClass {
   public void something() {
      out("called from super");
   }
}

public class SubClass extends SuperClass {
   @Override
   public void something() {
      out("called from sub");
      super.something(); // This is fine
   }

   public static void main(String[] args) {
      new SubClass().something(); // Calls both methods
   }
}

But I want to call the super.something() method from a different class:

public class SubClass2 extends SuperClass {
   @Override
   public void something() {
      out("called from sub2");
      new DecidingClass().maybeCallSuperSomething(this);
   }

   public static void main(String[] args) {
      new SubClass2().something();
   }
}

public class DecidingClass {
   public void maybeCallSuperSomething(SuperClass visitor) {
      boolean keepGoing = true;
      // Do some work, maybe set keepGoing to false
      // ...
      if (keepGoing) {
         // How do I call the Overridden method?
         visitor.something() // Causes recursive loop
         // visitor.super.something() ????
      }
   }
}

Is this possible? I have a work-around in place but it's a bit sloppy.

Upvotes: 0

Views: 482

Answers (3)

Ed Staub
Ed Staub

Reputation: 15690

This is a bit obvious, but... the usual way to deal with this is to extract the body of the base-class method into a separate method, so it can be invoked directly. You may want it to be final, both for performance and to emphasize that it's not to be overridden.

public class SuperClass {
   public void something() {
      doSomething();
   }
   public final void doSomething() {
      out("called from super");
   }

}

public class DecidingClass {
   public void maybeCallSuperSomething(SuperClass visitor) {
      // ...
         visitor.doSomething();
      // ...
   }
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425208

You can't invoke the super method - it's part of the java spec, but here's an (ugly) option:

public class SuperClass {

    public void something(boolean invokeSuper) {
        // do something
    }
}

public class SubClass extends SuperClass {

    public void something(boolean invokeSuper) {
        if (invokeSuper) {
            super.something();
        } else {
            // do something
        } 
    }
}

Upvotes: 0

Daryl Teo
Daryl Teo

Reputation: 5495

Short answer, no.

Superclass implementation is only visible to direct subclasses. External classes should not be aware of the functionality of individual implementations of a method anyway; coupling = bad.

Probably need to revisit your design if this is a necessity.

Upvotes: 3

Related Questions