Reputation: 2718
Java specification allows a class with default access to have its constructor public access, what is the purpose of it, since it cannot be referenced outside its package?
Upvotes: 3
Views: 229
Reputation: 3533
Class visibility determines how the outside world create instances of the class. hence package private classes can only be instantiated within the package they are declared. method visibility (including constructors) determines how the instance, already instantiated can be used outside its class definition.
If you declare a package private class, with a private/protected construtor, how will you instantiate it from another class in the same package?
Two things: class visibility - determines how instances are created outside their defining packages. method visibility (including constructors) - determine how the access to the members are controlled, regardless of package visibility.
Upvotes: 0
Reputation: 1756
I wanted to make this a comment, but since no code tags are allowed in comments....
In regards to your comment on CristopheDs answer:
package bob;
class MySuperHiddenClass {
public MySuperHiddenClass() {
System.out.println("bob");
}
}
And
package bob;
public class MyPublicClass extends MySuperHiddenClass {
}
No constructor was declared in MyPublicClass, but you can still call new MyPublicClass from any package.
Upvotes: 4
Reputation: 116307
If you are asking for why you can have public
constructors: it's because you can for example call them explicitely (or implicitely) when you extend a base class.
Upvotes: 2