Search code examples
javainheritancememoryjava-8static-methods

Java 8: Better to extend class of static methods or better to call static methods directly?


I'm updating some old Java 4 code to Java 8 (way too much to paste here) and the original programmer chose to have nearly every class of theirs extend this single HUGE class full of only static methods and constants, but I do not know their reasoning.

ex:

public class BaseClass{
     /* this class has a huge amount of ONLY static methods/constants */

     public static final int STUFF_DONE = 1;

     public static String getStuff(){
           String stuff = "this is my stuff.";
           return stuff;
     }
     ...
}

public class SuperClass extends BaseClass{
     /* this class has only a few methods */
     public String labelStuff(){
          return getStuff();
     }
}

public class MyClass extends SuperClass{
     /* there are many classes that extend SuperClass like this one */
     public int handleStuff(){
          String myString = labelStuff();
          return STUFF_DONE;
     }
     public static void main(){
          if(handleStuff()) System.out.println("Done.");
     }
}

My question is this... is it better to keep this design or is it better to remove the inheritance of the static methods/constants and simply call those methods/constants statically?

"Better" to me is defined as lower memory consumption (again, this base class is quite huge) as CPU is likely not affected by this. What are the benefits/pitfalls of this approach?

My concern is that because BaseClass is so huge that I'm wasting a LOT of memory for usage of only one or two methods/constants in the inheriting classes that I could just be calling statically.


Solution

  • Static members aren't "inherited" per se. They live on the base class regardless of which subclass they're called from, so I doubt there's any memory impact.

    The reason for creating all classes as a subclass of this common class is just for easy access to static members without the qualifying class name. A common variation is to inherit from an interface that declares a bunch of static fields. The upside is that implementing an interface doesn't interfere with inheritance the way a superclass would (you can only extend a single superclass). The downside is that until Java 8 it wasn't possible to declare static methods on an interface.

    In any case, this trick is generally considered an anti-pattern and has been superseded by static imports.