简体   繁体   English

类的构造函数

[英]Constructor of a class

I am having trouble understanding this. 我很难理解这一点。

"Lastly, modify WordTransformer and SentenceTransformer so you can not create an instance of the class. Remember, with static methods and variables, you do not need to make an instance of a class. (Hint: a constructor of a class is what allows an instance of that class to be created... new WordTransformer() , what keyword can you add to the definition of that constructor that will prevent the construct from being called anywhere but in the class itself?)" “最后,修改WordTransformerSentenceTransformer以便您无法创建该类的实例。请记住,使用静态方法和变量,您无需创建类的实例。(提示:类的构造函数允许创建一个类的实例。要创建的类的实例... new WordTransformer() ,可以在构造函数的定义中添加什么关键字,以防止在类本身之外的任何地方调用该构造?)”

It says so you can not create an instance of this class, but if you make the class private it becomes an error. 它说,因此您不能创建此类的实例,但是如果您将该类设为私有,它将成为错误。 Says the only options are public static or final. 说唯一的选择是public static或final。

well you shall qualify the constructor as private, not the class. 好吧,您应该将构造函数限定为私有而非类。 cf this document : cf 这个文件

Private constructors prevent a class from being explicitly instantiated by its callers. 私有构造函数可防止类的调用者显式实例化该类。

here's an example: 这是一个例子:

public class WordTransformer {
    private WordTransformer() {
    }
}

NB: as it sounds a lot like an assignment, I hope that you'll read the linked documentation and understand why and when to use it! 注意:听起来很像是一项作业,我希望您阅读链接的文档并了解为什么以及何时使用它!

将构造函数设为私有: private WordTransformer(){}

private WordTransformer(...) {
    ...
}

Making the constructor private will allow other methods of this class to create instances of the class but no one can create instances from the outside. 将构造函数设为private可以使该类的其他方法创建该类的实例,但是没有人可以从外部创建实例。 Example of when this is used in practice is the singleton pattern or builder pattern . 在实际中何时使用此示例的示例是单例模式构建器模式

标记为final的类的私有构造函数和静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM