英文:
Issues related to declaration of private constructor in a class
问题
我是Java的新手。
我正在阅读关于面向对象编程中的封装概念。
在阅读时,我看到了一句话:
> 如果类的构造函数被声明为私有,会引起一些问题。
但它没有说明会出现什么问题。
有人能告诉我私有构造函数会有什么问题吗?
英文:
I'm new to Java.
I was reading about Encapsulation concept in Object Oriented Programming.
While reading, I saw a line telling that :
> If constructor of a class is declared as private, it will cause some
> problems.
But it didn't tell what kind of problems could occur.
Can anyone tell what kind of problems are there with private constructor ?
答案1
得分: 1
当您将类的构造函数声明为'private'时,您将无法创建该类的新实例"对象"。如果您确实希望创建该类的新实例,这将是一个问题,但是在实现单例设计模式时,此方法非常有用。
如果您对了解更多关于设计模式的信息感兴趣,我可以与您分享一些资源。
这是Carlos E. Otero撰写的一本涵盖了设计模式主题的书籍:
https://books.google.com.tr/books?id=IL6FBLJn69UC&printsec=frontcover&redir_esc=y#v=onepage&q&f=false
英文:
When you declare a constructor of a class as 'private', you will not be able to create new instances "objects" of that class.
This is a problem if you do want to create new instances of the class, but this implementation is useful when making a Singleton Design Pattern.
If you are interested in knowing more about design patterns, I can share some resources with you.
Here is a book by Carlos E. Otero that covers the topic of design patterns:
https://books.google.com.tr/books?id=IL6FBLJn69UC&printsec=frontcover&redir_esc=y#v=onepage&q&f=false
答案2
得分: 0
声明构造函数为私有(private)后,就无法使用默认构造函数对类进行实例化。因此,您需要创建一个公有构造函数(public),以便在类外部访问它。
英文:
On declaring a constructor as private you can't instantiate the class using default constructor. So, you need to create a constructor with public to access it outside.
答案3
得分: 0
简单的词语,对象或实例不能为该类创建。
一旦您编写了以下语句。例如
SomeClass c = new SomeClass(); // 这将引发异常。
基本上,私有构造函数用于创建单例类。
英文:
Simple words, object or instance can't be created for that class.
As soon as, you write this statement below. For example
SomeClass c = new SomeClass(); // this will give an exception.
Basically, private constructors are used for making singleton classes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论