正确的方法来防止在Java中实例化 [英] Correct way to prevent instantiation in Java

查看:194
本文介绍了正确的方法来防止在Java中实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们想要防止在Java中实例化对象,我们可以使用几种方法,其中最明显的是:



  1. private / protected constructor

让我们假设类不包含抽象方法, > abstract 关键字,以防止创建对象。这种方法不正确(我的意思是不是语法正确,但语义)?



UPD
类将是其他的基类,虽然它不包含抽象方法。在我的例子中,它有一些AbstractTestBase,它包含一些常见的数据和实用程序方法,可以被一些集成/单元测试使用。

解决方案

由于你想使用类作为子类,建议'final类与私有构造函数'将不会明显地工作,所以你必须去'抽象'的方式。从'抽象类'的定义,这是legetimate,因为定义完全规定你想要的:


抽象类是一个类这是被声明的抽象 - 它可能或可能
不包括抽象方法。抽象类不能被实例化,
,但它们可以被子类化。



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



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.

解决方案

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

这篇关于正确的方法来防止在Java中实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆