0

https://www.javatpoint.com/strategy-pattern

I have heard that we can't initiate (make objects) of interfaces, but in Strategy Pattern, we are creating an object of Strategy interface.

Code

public interface Strategy {  
      public float calculation(float a, float b);  
}
public class Context {  
  
       **private Strategy strategy;**  
       
       public Context(Strategy strategy){  
          this.strategy = strategy;  
       }  
  
       public float executeStrategy(float num1, float num2){  
          return strategy.calculation(num1, num2);  
       }  
}

In context class, we have created an object of Strategy interface. How is this possible as interfaces can't be instantiated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ChirAdi
  • 43
  • 5
  • Check the second answer, it should help :) [here](https://stackoverflow.com/questions/3528420/why-do-we-need-interfaces-in-java) – Tobias Cremer Dec 25 '21 at 11:32
  • The code shown doesn't create any objects. In any case, `Context` will be passed an instance of a concrete implementation of `Strategy`. – Mark Rotteveel Dec 25 '21 at 11:38
  • No object of `Strategy` is created anywhere. You defined the constructor so that it can take any instance that implements `Strategy` as parameter. – QBrute Dec 25 '21 at 14:19

0 Answers0