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 ?