Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个只有静态方法和字段的 java 类,所以我不希望为此创建任何对象。我可以通过两种方式实现这一点,
两者哪个更好?
您应该使用private构造函数。
private
如果您的类是抽象的,则可以对其进行扩展并创建对象。根据我对问题的理解,您想要的是不可实例化的类。
来自Effective java 的第 4 项:
试图通过使类抽象来强制执行不可实例化是行不通的。该类可以被子类化并且子类可以被实例化。此外,它误导用户认为该类是为继承而设计的