简体   繁体   中英

Preventing object class creation

I've been reading the article about constructors and what have been written there is:

A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and by declaring no constructor that is public.

I'm confused by declaring no constructor that is public . This is because if we don't declare any constructor at all the implicitly-declared default constructor will be implicitly declared with an access modifier of the class. Which means if the class declared as public, the default constructor will be public too. That's we can use it outside the package (create instances outside the package).

You missed this bit:

by declaring at least one constructor

That's what's preventing the default constructor from being created.

The example given has a default access (package access) constructor:

PackageOnly() { }

... so it satisfies both conditions: a) it declares at least one constructor; b) it declares no public constructors.

不可以,该类可以公开,但是构造函数只能针对包访问protected ,也可以是private -主要与工厂静态方法一起使用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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