Reputation: 61
In Java I see sometimes the constructor declared as 'public' and sometimes it has no access modifier meaning it's package-private. What are the cases in which I must use one over the over and vice-versa?
Upvotes: 6
Views: 16897
Reputation: 240870
Modifiers applies to constructor same as fields and method.
public
, any class can access and see it.private
, no other class outside that class can access or see it.Read more about access control at documentation
Generally constructors are made private
when you use Factory pattern or Singleton pattern
Upvotes: 1
Reputation: 147154
"Package private" (default access), despite being the default, is rarely a good choice other than on outer class/interface/enum. It would be appropriate for an abstract class with a fixed set of subclasses (in the same package), a bit like an enum
constructor in the same enum. If the outer type is package private, you might as well leave public constructors and members public rather than a more exotic access modifier.
Upvotes: 0
Reputation: 43088
The question contains the answer. Make the constructor public if you allow your client code outside the package instantiate your object. If you don't want that( because object is package specific or the object itself can't be instantiated directly ) use package-private.
For example, if you have a client code that should use a Car
( which is an interface ) and some package com.company.cars
contains classes, which implements the Car
interface( BMW, WV, Opel
) and so on, then you would rather have a factory which instantiates necessary Car implementation. So, only the factory would have access to the constructor.
public CarFactory {
public Car getCar(CarType carType) {
Car result = null;
switch(carType) {
case BMW:
result = new BMW();
case Opel:
result = new Opel();
}
return result;
}
}
class BMW implements Car {
// package-private constructor
BMW();
}
Upvotes: 4