Mihail Slavchev
Mihail Slavchev

Reputation: 397

Java public class with public constructor with non-public parameter. Why?

Java allows to define the following pair of classes.

class Class1 { ... }
public Class2 { public Class2(Class1 c1) { ... } }

Why Class2 has public constructor if I cannot instantiate it because Class1 is not accessible?

For the record, there are no public classes that inherit from Class1.

Upvotes: 0

Views: 405

Answers (4)

Marco13
Marco13

Reputation: 54639

At the first glance, it seems like it does not make sense: A user of this package may access Class2. But he can't create an instance of Class2, because he has no access to Class1. So there is no reason of making the constructor public, when the argument that it needs is not public as well.

The only situation where this actually makes sense is when there is another public class in the same package that extends Class1. Then you could create an instance of this class, and pass it to the constructor:

// Assuming this class extends Class1, and it is public, you 
// can create an instance of this class from outside the package:
ExtendedClass1 e = new ExtendedClass1(); 

// This is using the public constructor that expects a Class1.
// Although Class1 itself is NOT public, this constructor 
// can be called with an instance of a (public) class that
// extends Class1
Class2 c = new Class2(e); 

But since the latter was excluded in the question, there is no reason to have this public constructor.

Upvotes: 2

Sean Landsman
Sean Landsman

Reputation: 7179

It is reasonable to have a class that limits its creation/access to members of the same package with a view that other classes in the same package will extend this class and be made public.

For example if you were implementing the Template pattern you might have super class (probably abstract) that implemented the base, shared, logic, with one or more concrete classes that implemented the the differing steps.

These concrete classes could then be instantiated by callers, but the base class wouldn't.

Arguably though the base class could equally be protected instead of package scope.

Upvotes: 0

prady00
prady00

Reputation: 741

Every class has a default constructor(if you do not provide one) you can do :

Class1 c1 = new Class1();

then

Class2 c2 = new Class2(c1);

Upvotes: -1

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Class1 and Class2 are defined in same package. So they can be accessible. Class1 has default access modifier, which is visible to all Classes inside the same package

Upvotes: 2

Related Questions