防止默认构造函数在Java中使用?
在我的评估中,它说:
"We don't want the user to use the default constructor since the user has to specify the HashCode, and maximum load factor"
我以为这可以解决问题,但显然不是(字典是一个用于抛出异常的类):
public boolean HashDictionary() throws DictionaryException {}
字典异常类:
public class DictionaryException extends Throwable {
}
测试以确保在使用默认构造器时抛出异常(由讲师提供):
try
{
HashDictionary h = new HashDictionary();
System.out.println("***Test 1 failed");
}
catch (DictionaryException e) {
System.out.println(" Test 1 succeeded");
}
我只是想知道我该怎么做,因为我不熟悉这样做的方法。谢谢。
如果您不希望调用默认的,则可以将其声明为私有的。
要回答您的评论,您可以抛出一个异常-
public HashDictionary() throws DictionaryException {
throw new DictionaryException("Default constructor is not allowed.");
}
你可以
a) 省略默认构造函数
b) 使默认构造函数私有
c) 使用默认构造函数时引发异常
public HashDictionary() throws DictionaryException {
throw new DictionaryException("Default constructor should not be used!");
}
不要那样做。只需将默认构造函数设为私有:
private HashDictionary() {}
编辑:boolean
在构造函数定义中做了什么?我只是复制了它...
用户使用默认构造函数,则可以在声明其他非默认构造函数时省略构造函数,也可以使默认构造函数private
。
您可能遇到的另一个问题是,您在问题中放置的声明不是构造函数,而是一种方法。构造函数没有返回类型。
更改此内容
public boolean HashDictionary() throws DictionaryException {}
对此
public HashDictionary() throws DictionaryException {}
更好的是将其更改为
private HashDictionary() {}
然后没有人可以在类本身之外访问它。
我最终添加了这个:
public DictionaryException(String error_string)
{
System.out.println(error_string);
}
作为字典异常的默认构造函数
然后:
public HashDictionary() throws DictionaryException {
throw new DictionaryException("Default constructor should not be used!");
}
对于 HashDictionary 的默认构造函数,问题是该类型是布尔值,所以我删除了它,它似乎有效。
-
若要禁止从类外部调用默认构造函数,请使用:
private HashDictionary(){}
-
若要禁止从类内部调用默认构造函数,请使用:
声明参数化构造函数,不要在类中编写默认的非参数化构造函数。 公共哈希词典(字符串字符串){ }
-
如果您希望在调用构造函数时引发一些异常,则:
public HashDictionary() 抛出异常 {
抛出新的异常("从构造函数抛出异常");
}
问候,比兰德拉。
使用默认构造函数,但要实例化类,则需要实现自定义构造函数。您必须告诉用户创建有效实例需要什么。就是这样!默认构造函数将不再可用。如果构造函数逻辑太复杂,请随意提取私有方法,包括私有构造函数,如果您认为它在您的情况下是可以的。如果您有多种创建实例的方法,则可以使用类似工厂的静态方法和私有 ctor。制作一个私人 ctor 只是为了禁用默认的 ctor 是没有意义的(至少我没有看到)。
如果您不想实例化一个类(我的意思是您不想使用默认的 ctor,并且您没有理由创建自定义 ctor),这意味着您只想使用静态字段/方法,因此请将整个类设为静态。
哦,我假设我们谈论的是非抽象类。