What should be a helper class declaration using only static methods?

I have a class here that contains only methods static, so I call it a helper class, for example:

public class FileUtils {
    public static String readFileEntry(final Path path, final String entryKey) throws IOException { }

    public static String readAndModifyFileEntry(final Path path, final String entryKey, final UnaryOperator<String> operator) throws IOException { }
}

How to declare a class ( abstract, final, staticetc.), it is impossible to create an instance of the class? How you should not do it.
If this is not possible, then what is the best practice?

I am using Java 8 if this helps.

+4
source share
4 answers

You can declare the constructor as private and use the final keyword to prevent extensions:

public final class FileUtils {
    private FileUtils() {
    }

    public static String readFileEntry(final Path path, final String entryKey) throws IOException { }

    public static String readAndModifyFileEntry(final Path path, final String entryKey, final UnaryOperator<String> operator) throws IOException { }
}
+3
source

This is a common template:

public final class Helper {

    private Helper() {}

}
+3
source

final , . , , :

public final class FileUtils {

    /** Empty private constructor, just to prohibit instantiation */
    private FileUtils() {}

    // Rest of the class...
}
+3

static . final , . abstract . , abstract. - :

public class FileUtils {
    private FileUtils() {
        // empty constructor needed just to make it impossible to write new FileUtils()
    }
}
+2

Source: https://habr.com/ru/post/1533679/


All Articles