views:

928

answers:

5

I think in this case there is no need to declare a public constructor since the class is not accessible outside the package anyway. But is there some hidden impact when the class has only package private constructor?

+10  A: 

No, you don't have to declare the public constructor; package private constructors will be just as usable. Classes outside the package wouldn't be able to use the constructor anyway, since they can't see the class.

Jorn
A: 

You need a public constructor, to create instances of the class. But access is restricted to classes from the same package. A private constructor - as usual - for classes that you don't need to construct external from the class: classes with only static methods and classes that export instances as public fields or via methods (i.e. Singletons).

Mnementh
A: 

Indeed, if your class is package private, the states public o package private of the constructor are equivalent. However, you can yourself, which behaviour you want to have when you change a class visibility during development : this can happen when you open some APIs which were previsouly internal, then it looks more conservative to have put the construvtor as package private since you do not open all doors at the same time.

Denis R.
A: 

A related question for you to think about.

Should a public abstract class have a public or protected constructor?

Peter Lawrey
Is this the Socratic method? Because it doesn't _look_ like an answer.
Michael Myers
It the answer is given. I was pointing out that there are common cases where constructors are made public when another modifier might make be clearer.
Peter Lawrey
A: 

we cant made a constructor public in a private class because private class cant be accessed outside and none of its methods can be accessed and as constructors are special members functions so it can also not be accessed from outside so it cant be declared public because it ultimately violates the private definition of class

anil