Question

This is the header of my abstract class

public abstract class RecursiveGo extends JFrame implements ActionListener

I want to take a method from this class, which is non static, and call it in the main method of the driver of this class. I have not yet made the driver, but I know that if I extend this class into the driver and make the driver a subclass it will come up with an error because I will not be overriding actionlistener. How can I call a non static method from this abstract class in a non abstract driver?

Was it helpful?

Solution

If there is a useful non-static method that depends on a subset of the class (i.e. that doesn't depend on ActionListener), but the entire class has to stay abstract, it sounds like there's a clean line of separation there. Refactor the class to extract the subset, and make it available to your driver.

public abstract class RecursiveGo extends JFrame implements ActionListener {

  private final UsefulSubset usefulSubset;

  public RecursiveGo() {
    usefulSubset = new UsefulSubset();
  }

  // Static, so you can address it as RecursiveGo.UsefulSubset.
  // Maybe it extends JFrame, too, and if made a top-level class
  // then RecursiveGo could further subclass the subset.
  public static class UsefulSubset {
    void methodCall {}
  }
}

class YourDriver {
  public static void main(String[] args) {
    RecursiveGo.UsefulSubset instance = new RecursiveGo.UsefulSubset();
    instance.methodCall();
  }
}

Of course, maybe that useful subset could stand on its own as a top-level class, which would be even better. The code is malleable, and if it's not shaped the way you like, feel free to change the shape.

As ajb notes in the comments, see if making the method static would be worthwhile. Personally I favor dependency injection and mocking frameworks, so I'm not a fan of moving mountains to making methods static, but of course that would be a simple solution to your problem.

OTHER TIPS

Create an instance of RecursiveGo inside its driver that shall be the instance of its driver(sub class) ,as we cant instantiate the instance of abstract class. Then call that non static method of created object and see if that solves your problem.

You technically can't do what you are asking within Java. Since a class that implements an interface MUST define the methods in that interface, you have to either define that method, or think of another way to do what you are trying to do altogether. For example you could try having the RecursiveGo not implement ActionListener, and then extend RecursiveGo, and then to still have an ActionListener - you would use a provided default ActionListener (if one exists).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top