Static methods in abstract class?

Viewed 112

I recently learned from a video that it's a good practice to turn a Java class into abstract if all of its methods are static for performance reasons.

Can anyone explain why this is the case?

2 Answers

This is likely to prevent people from creating instances of the class. Java code is expected to create lots of objects that are useful for a short time and get garbage-collected, so it is hard to say this is any kind of substantial performance win. It seems more like a way to communicate the intention behind a class.

Another alternative is, instead of making the class abstract, make the class final. This is the approach taken in JDK code, for instance, java.lang.Math:

public final class Math {

    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {}

With either of these approaches you should give the class a private constructor. That prevents anyone from instantiating it and makes it clear the class's purpose is to provide a home for the static methods. The downside here is code coverage tools tend to report the constructor as uncovered.

A third alternative, as of Java 8, is to put the static methods on an interface. Any methods with an implementation that aren't default get assumed to be static methods. The advantage of that approach is there is no constructor to make private, and the code coverage tools will be happy.

With an abstract class (but without the private constructor), or an interface, there is also the possibility of extending or implementing the type to make all the static methods available without static imports. See this link for an example. With the java.lang.Math approach that isn't an option.

You don't have to make it an abstract if it has static methods. if you make it an abstract class then no one can instantiate this class.

on the other hand, you can declare a class with a private constructor, so no one, not even a subclass, can instantiate an instance of your class.

 public class A
 {
    private A()
    {
       throw new RuntimeException("Instantiation of MyUtility is not 
       allowed!");
     }

    public static void aMethod()
    {
      // Your method here.
    }
  }
Related