Search code examples
javainheritanceinterfacestaticclassloader

Import or Implement Reusable Statics?


Option #1:

public class WidgetStatics {
    public static final String FIZZ = "fizz";
    public static final String BUZZ = "buzz";
}

And then:

import com.me.myorg.myapp.WidgetStatics

public class Thing1 {
    public void doSomething() {
        String x = getValueFromUser();
        if(x.equals(WidgetStatics.FIZZ))
            // ...
    }
}

Option #2:

public interface WidgetStatics {
    public static final String FIZZ = "fizz";
    public static final String BUZZ = "buzz";
    // ...
}

And then:

public class Thing2 implements WidgetStatics {
    public void doSomething() {
        String x = getValueFromUser();
        if(x.equals(FIZZ))
            // ...
    }
}

My questions:

  • Is one option more performant over the other? Which causes more exertion from the ClassLoader: importing or implementing?
  • Are there specific use cases where one approach is more desirable/cleaner than the other?

Solution

  • There are always more than one way to solve a particular problem.

    Interfaces were introduced in Java to solve certain design issues. One was of-course the popular Multiple Inheritance problem. The other important scenario where Interfaces are used is when you would want to design a class structure in which certain classes must abide by contracts defined in Interfaces (and hence they would need to implement related Interface(s)).

    Since in your case you do not seem to enforce any such contracts or design suggestions, I'd suggest you do not use an Interface for this.