46

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?

7
  • 5
    Why do you want to make the class abstract? Abstract class means that there are some declared but unimplemented methods, which extending classes must implement. Commented Mar 8, 2012 at 13:46
  • 9
    @Aleks G: That is not true... Abstract class means: You cannot directly instantiate it. You don't neccessarily HAVE TO define abstract methods within that class... Of course you are right. Normally you would use abstract classes like you said. But that is just a "point-of-view" thing. I always make my larger factory classes abstract without defining abstract methods. Commented Mar 8, 2012 at 14:36
  • 1
    @AleksG you don't have do define abstract methods on an abstract class. Its an oddity... Abstract means the class cant be directly instantiated and that its child classes must implement it's abstract methods or declare them abstract too. Commented Jun 7, 2013 at 11:47
  • 2
    @Sauer I have also came to a point when I NEEDED to declare a 'namespace', a class just to contain static methods and variables accessible from any part of my code and it shouldn't be able to be instantiated nor inherited. I think there's nothing wrong on declaring a 'final abstract' class, java language definition seems to be a bit broken at that point. Perhaps they could add 'final abstract' definition and enforce all of the class' fields to be static. Well, that would surely be an agression to OOP standards XD Commented Jun 7, 2013 at 11:51
  • 2
    Ah and also, C# seems to have the "static class" concept, which seems to be the exact concept the OP intended to describe. Commented May 30, 2016 at 17:46

9 Answers 9

61

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)

Sign up to request clarification or add additional context in comments.

11 Comments

it is perfect solution. I do not understand why people do not vote it.
Peter Lawrey 1 - 0 Joshua Bloch ;-) (Funny that JB does not mention that when he advocates using enum so strongly for singletons)
It does mean that the type does come with some rather odd static and instance methods.
@Sauer If you don't use methods, they have no over head. It worth thinking about your overhead writing code you don't need to.
using an enum is better than the accepted solution, as it does not leave unreachable code that cannot be covered by unit tests (unless one uses reflection)
|
48

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() {} } 

8 Comments

@LuiggiMendoza this is not a singleton pattern. There is no instance at all here.
Yes, but Singleton Pattern could be a suited solution for this.
I'd make it final, not that that should make any difference since JDK6/J2SE 5.0.
@TomHawtin-tackline Edited - I agree it is better from a readability perspective even if it does not make a difference.
Well, a class can be within this class and use the private constructor, the final could make a tiny bit of difference there. That said, if somebody wants to muck about in your class then there is no stopping them. The assertion error can be left out, only creates unreachable code, I normally use a comment instead.
|
8

No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)

final class MyLib{ private MyLib(){ throw new IllegalStateException( "Do not instantiate this class." ); } // static methods go here } 

5 Comments

@assylias: "the class will be final because it can't be subclassed". It depends on your definition of "final". It's not as if the class was implicitly made final because of the private constructor (in the way, say, interface methods that aren't declared as public are implicitly public). Putting for example public final or simply public shall lead to two different .class files being generated: with final the .class has its access flags set to 0x31 (public final) while with only public its access flags are 0x21. You cannot extend it but it's still not final...
@ArtB But you would agree, that the following is also nonsens?: The alternative would be, to write an "object-class" and call the constructor once, which does all the work... There is no point in using this object any further. It has no destructor, no getter, no setter... The object is pointless in this case, because all objects will be exactly the same. This is exactly, what static methods are for. And it is good practice, to encapsulate stuff into separat classes (i.e. "files"). Of course I can stuff everything in my calling class. But that would be too much...
@Sauer It's hard to offer an alternative without knowing specifics, but after working on becoming better with object-oriented design principles I find that very rarely are static methods needed. The only cases I can really justify are those where you are adding methods that ought to have existed in the class or are for dealing with null issues.
@ArtB Of course it is up to you, how you design your structure. But to me, static methods are a very valid part of each object oriented programm. I also write APIs at my company and I often use static methods to ENFORCE object oriented coding. Static methods are used to handle "static" and complex algorithms which are working WITH objects. That keeps the real object classes less complex and easier to understand (pojos). Sometimes there is no point in stuffing complex algorithms into object classes...
@Sauer I would recommend you at least try stuffing those algorithims into objects as an excercise. I've found that over time I've found neat ways to include those algorithims in to objects, or that some design pattern solves this. I suggest that it maybe be correct more often than you suspect to push things into objects from static methods. YMMV
4

No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!

Comments

3

Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.

Comments

1

The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.

However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.

I suggest the following:

public abstract MyClass { protected MyClass() { } abstract void noInstancesPlease(); void myMethod() { ... } ... // More private methods and fields... } 

This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).

It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.

I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.

1 Comment

I got your point and it made me think about my design. But in my case, I really really don't want to let someone extend my class. That is why it is default visibility "final class MyClass" (without public). It is only valid within my package and noone should be able to use it outside that package. And noone should be able to extend it inside the package. But anyway: Nice idea with that "noInstancesPlease" abstract method... I will keep that in mind
1

You can't mark a class as both abstract and final. They have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.

Comments

-1

This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?

1 Comment

You are right. But, as I said: I want to use this class for a Toolbox of static methods. So I neither want to instatiate, nor to extend it.
-3

Check this Reference Site..

Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

Thanks..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.