Correct way to prevent instantiation in Java [closed]

穿精又带淫゛_ 提交于 2019-12-10 13:46:50

问题


If we want to prevent instantiation of object in Java we can use several approaches and most obvious of them:

  1. abstract keyword
  2. private/protected constructor

Let's say class doesn't contain abstract methods and we use abstract keyword to prevent creation of the object. Is this approach incorrect(I mean not syntax correctness, but semantic )? Or it's better to use private constructor in such cases?

Thanks

UPD Class will be a base class for other, though it doesn't contain abstract methods. In my case it some "AbstractTestBase" which contains some common data and utility methods which can be used by some group of integration/unit tests.


回答1:


As you want to use the class as subclass, the suggestion 'final class with private constructor' will not work obviously, so you'll have to go the 'abstract' way. From the definition of 'abstract class', this is legetimate, as the definition exactly states what you want:

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html



来源:https://stackoverflow.com/questions/14183110/correct-way-to-prevent-instantiation-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!