Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
May 5, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Package Protected Constructor

I need to extend class A which resides in a different package, but class A has only one constructor which is package protected. I get a compile error in class B, which extends class A, saying that the class A constructor is not visible from class B. I know this is correct, but how do I extend and initialize class A and access its package protected fields?

If you have written the source code to class A, then you are in complete control and can resolve the problem. If class A was intended to be subclassed outside of its package, then you have run into a design problem. Any class that is intended to be extended by classes outside of its package should declare most of its members either public or protected. Members which are to be publicly accessible, but not polymorphic should be declared final. Members which comprise the external interface exported by the class should be public. Members which are not part of the external class interface, but which are needed by subclasses should be declared protected. Only if you want to limit subclassing or use to a particular package should a constructor or other members be declared package local. Additionally, in some cases, you may want classes in a package to liberally access each other's package local member variables for performance reasons. Finally, member functions and variables which are only to be accessed by the class should be declared private.

It is a common practice in C++ and Java to declare a constructor protected if you only want subclasses to be able to use the class. In Java, you may declare a class constructor package local in order to limit its use to a particular package. If you are finding you need to subclass such a class outside of its package, you should redeclare its constructor protected. If you need to instantiate such a class outside of its package, you should redeclare its constructor public. It also may be that your class B should be placed in the same package as class A if the original design decision to limit access to class A to within the package was sound.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date