Home > database >  How could I call an abstract class method who is common between subclasses without instanciating any
How could I call an abstract class method who is common between subclasses without instanciating any

Time:10-23

I have a code like this :

interface Contract {
  createSomething(); //not common
  updateSomething(); //not common
  getSomething(); //method who is supposed to be common between all strategies
}
interface Strategy {
  createSomething();
  updateSomething();
  getSomething();
}
Abstract class AbstractStrategy implements Strategy {

  @Override
  getSomething() {
    // the common code
  }
}
class strategyA extends AbstractStrategy {

  @Override
  createSomething() {...}

  @Override
  updateSomething() {...}
}
class ContractImpl implements Contract {

  @Override
  createSomething() {
    //get the good strategy 
    //call the strategy.createSomething();
  }

  @Override
  updateSomething() {
    //get the good strategy 
    //call the strategy.updateSomething();
  }

  @Override
  getSomething() {
     **Here is the question**
  }
}

Question:

  • How could I rewrite this code so I could call the getSomething() method without having to instanciate a random subclass just to call it with the super keyword ?

CodePudding user response:

You can't. Rather, you could extract the code into a static method and subsequently call it from getSomething(). This would allow you to call it statically when you need to, and from an instance when needed as well. In other words, your AbstractStrategy class should look like:

Abstract class AbstractStrategy implements Strategy {
    public static void sharedCode(parameters needed) {
        // the common code
    }


    @Override
    (signature) getSomething() {
        sharedCode(this.parametersNeeded);
    }
}

CodePudding user response:

You basically can't. An abstract class can't be instantiated, so you can't call an instance method without having an object of a concrete implementation (in your case any concrete subclass of AbstractStrategy).

One option that you have is to create an anonymous class so that you can call the method without instantiating any of your subclasses of AbstractStrategy:

AbstractStrategy strategy = new AbstractStrategy() {
  @Override
  createSomething() {...}

  @Override
  updateSomething() {...}
}
strategy.getSomething();

But this feels hacky.

  • Related