37

I have a java class which has only static methods and fields, so I don't want any object to be created for that. I can acheive this in two ways,

  1. make class abstarct.
  2. use private constructor.

Which of the two is better way?

  • 8
    You can take a look at the `java.lang.Math` class (which have only static fields and methods). They made the constructor private. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Math.java. Make sure your class is final too. – Alexis C. Dec 15 '13 at 10:00
  • +1 for comment, our general queries can be found in java libraries itself. – codingenious Dec 15 '13 at 10:03

1 Answers1

58

You should go with private constructor.

If your class is abstract, it can be extended and objects can be created. As per my understanding from the question, what you want is non instantiable class.

from Item 4 of Effective java :

Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
codingenious
  • 8,385
  • 12
  • 60
  • 90
  • 1
    The link is inaccessible, perhaps only suitable if you are a subscriber to Safari Books Online. Here is a blog on this subject though: https://medium.com/@biratkirat/learning-effective-java-item-4-4bc457fc5674 – Jaap May 01 '18 at 11:38