1

I have an interface:

public interface Condition {

    boolean check();

    JSONObject toJSON();

    Condition fromJSON();
}

And i need to ensure that, every implementation of this interface overrides method fromJSON and i need that method to be static. Is there any way how to do that??

I tried making that method static in the interface, but it does not work as i want.

I also dont want to make it abstract class as every implementation has different functionality of the method.

Is there any other method ho to ensure that every implementation has static method fromJSON ??

  • Why do you need it static in the first place? – Gilad Green Jul 20 '17 at 15:05
  • leave interface and just go for abstract class and extend that class in your respective class. – shreyansh jogi Jul 20 '17 at 15:06
  • @shreyanshjogi that will still not help to ensure that there is an override for a static method. – RealSkeptic Jul 20 '17 at 15:06
  • @GiladGreen Because i want it to return object from the provided json. But now as im thinking of it i can possibly make other object to do this functionality for me but isnt there any other option ?? – František Jeřábek Jul 20 '17 at 15:07
  • static methods and an interface don't mix. When you stop and think about it, a static method would be declared only once, which defeats the purpose of an interface. – Dakoda Jul 20 '17 at 15:09
  • Static methods as part of an interface don't make sense. We use interfaces to say "as long as an object fulfills this contract, I don't care what it is, I know I can work with him". It's part of polymorphism. With static methods, there *are no objects* so we can't use them polymorphically. – Michael Jul 20 '17 at 15:30

1 Answers1

1

In short, no. Really, the purpose of an interface is so that you can refer to all classes that implement that interface under a generic single name and still be sure that specific methods are available. For instance, in your case, you could have an array of Conditions, and then loop over them and each time call condition.toJSON(). But static methods are always accessed from the class name. If you have a class that implements Condition called RealCondition, and you wanted to build a RealCondition from JSON, you'd need to already know that the output object you want is a RealConditon, and thus there'd be no point in having the fromJSON method under the generic name Condition.

Tim M.
  • 598
  • 5
  • 15