I fount a util class in Spring named NestedExceptionUtils, and it is declared as an abstract class, why abstract? To prevent instances of it? But another class is not declared as an abstract class! Such as 'BeanDefinitionReaderUtils'. when should I do this?
1 Answer
NestedExceptionUtils
contains a single public static
method and has no derived classes (within Spring). This suggests that it's abstract
to prevent instantiation.
Another and a slightly better way to create utility classes in Java is to declare a class final
and define a private
no-args constructor. This is better than abstract
utility class because it also suppresses extend
ing the utility class.
Spring wasn't written by a single person, this could explain why different utility classes are written in different ways.
-
1.the two example class are written by the same person named 'Juergen Hoeller', there is no reason two classes have a different style. 2.even if they are written by different people, don't spring team has a common style limited? I'm confused! Dec 24, 2018 at 15:08
-
Well, the author would be the best person to ask for the reasoning, of course. But note that
BeanDefinitionReaderUtils
has becomeabstract
as well in Spring version 5.1.2.RELEASE. Dec 24, 2018 at 16:18
abstract
. Utility classes are generallyabstract
and have aprivate
no-args constructor to prevent sub-classing.