如何防止在 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 {}
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");
}
我只是想知道如何做到这一点,因为我不熟悉这样做的方法。谢谢。
最佳答案
如果您不希望调用默认值,可以将其声明为私有(private)。
要回答您的评论,您可以抛出异常-
public HashDictionary() throws DictionaryException {
throw new DictionaryException("Default constructor is not allowed.");
}
关于java - java默认构造函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19497299/