简体   繁体   中英

abstract class vs private constructor

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM