Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java final abstract class

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?

like image 617
Sauer Avatar asked Mar 08 '12 13:03

Sauer


People also ask

Can a abstract class can be final?

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.

What is final class and abstract class?

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.


2 Answers

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)

like image 193
Peter Lawrey Avatar answered Sep 18 '22 19:09

Peter Lawrey


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() {} } 
like image 28
assylias Avatar answered Sep 22 '22 19:09

assylias