Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a common static method in all classes implementing an interface

I have an interface called Relation, implemented by a class BasicRelation, and extended by subclasses (e.g. ParentChild, Sibling, Spouse). While developing my code, I realized that I often need a method which takes a String representation of a relation to create it. For example:

public class ParentChild implements Relation extends BasicRelation {

  // e.g. "Jack is Emily's father. Jill is her mother." will return the list
  // <ParentChild(Jack, Emily), ParentChild(Jill, Emily)>
  static List<ParentChild> fromSentence(String s) {
    ...
  }
}

Now, since I find myself needing this method (fromSentence(String)) in every class, except perhaps in BasicRelation, I would like to move it up the hierarchy. The problem is that the internal details of the method is subclass-dependent, so I can't have it as a static method in the interface Relation or the superclass BasicRelation.

Unfortunately, in Java, it is also not possible to have a static abstract method.

Is there any way to ensure that every subclass of BasicRelation (or every class implementing Relation) implements fromSentence(String)? If no, should I be designing this in a completely different way? I guess this last question is more of a request for design-advice than a question.

like image 474
Chthonic Project Avatar asked Mar 22 '26 15:03

Chthonic Project


1 Answers

Why does the static method need to be in the interface? What's stopping you from having a 'Utility' class and having the method in there?

public class RelationUtility {
    public static BasicRelation relationFactory(String asString) {
        ....
    }
}

As a static method, there is no reason other than access to private members, which can also be accomplished by by 'default' permissions on those members....

like image 163
rolfl Avatar answered Mar 25 '26 05:03

rolfl