I have a quite simple question:
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass { static void myMethod() { ... } ... // More private methods and fields... }
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
An abstract class is a class declared with an abstract keyword, which is a collection of abstract and non-abstract methods. But, the final class is a class declared with the final keyword, which restricts other classes from accessing it. Thus, this is the main difference between abstract class and final class in Java.
You can't get much simpler than using an enum
with no instances.
public enum MyLib {; public static void myHelperMethod() { } }
This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention //private default constructor ==> can't be instantiated //side effect: class is final because it can't be subclassed: //super() can't be called from subclasses private MyClass() { throw new AssertionError() } //... public static void doSomething() {} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With