Is exposing static methods in abstract classes considered good or bad practice

robbie70 :

I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?

I've produced a simple example program to illustrate what I mean.

public abstract class StaticMethodsInAbstractClassesStudy {

    public static int adder(int a, int b){
        return a + b;
    }

}

public class StaticMethodsInClassesStudy {

    public static void main(String [] args){

        System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));

    }
}

When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.

I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.

Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?

JB Nizet :

It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305327&siteId=1