开发者

Aren't Java constructors public by default? [duplicate]

This question already has answers here: What is the default access specifier in Java? (12 answers) Closed 7 years ago.

I have two classes in two different packages. For one class I've defined a constructor without setting access modifier for it. I want to instantiate an object of this class in another package and get the erro开发者_如何学运维r 'the constructor xxx() is not visible'.

If I define access modified to public it is fine. I thought constructors are public by default?


no access specifier != public

No Modifier is package private. check doc


No, they're not. They have package-visibility by default.


Access is (err...) default access by default. Also known as package private. Consider: if they were public by default, how would you indicate that a constructor was not public but in fact was package private? There is no keyword corresponding to package private with which to indicate that.


You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. If you don't declare the constructor explicitly as public it is visible only in the same package where it was declared (package access).


When you don't write access modifier it is set to default, which means package private. E.g. no class outside the package can access it.


No. they have the default access specifier. i.e they have package visibility.


In a class all method without access modifier have package visibility. However, in interfaces methods always have public visibility.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜