Yaroslav
Yaroslav

Reputation: 1375

How to make a member of a class to be accessible only in subclasses in any packages?

How to make a member of a class to be accessible only in subclasses in any packages? Protected is not a solution since it will open the member to other non subclasses classes.

Upvotes: 0

Views: 960

Answers (4)

fxrbfg
fxrbfg

Reputation: 1786

You could do abstract class with protected member, and implement it in another packages. Consider you created some lib and design extensability for certain things. Later users of your lib will implement realizations of your class and has access to protected member and in same time not able to create implementation classes in your package. In example FilterReader class, it design for extensibility, after you implement it in somewhere in your code outside java.io package that protected fields and methods will be private to other classes in your package.

Upvotes: 1

Brick
Brick

Reputation: 4262

Java does not provide absolute encapsulation. Some amount of discipline is required on the part of the programmer - both the original designer and anyone that uses a published API - to abide by some rules that are outside of the language. Regarding member access, you have identified one such case. What you want is not possible in Java.

Just to put this in broader perspective, I'd point out that even private members can be accessed by other classes if a programmer is willing to go far enough to do it. Calls made via JNI do not have to respect any of the access modifiers. See, e.g., Can a native method call a private method?

Other examples of out-of-language norms include the contract for equals/hashCode, which must be met for classes to behave well with respect to collections but is not enforced at the level of the language.

Upvotes: 1

DBJamesH
DBJamesH

Reputation: 11

What you are trying to achieve ist not possible during to acces control:

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

You may rethink your software design, since yout problem is caused by architecture. please be more specific in your question for getting further answer.

Solving your problem may cause sideeffects and is not in a OOD manner.

The only way to acces the private member is using an getter method with same visibilty issuses.

Upvotes: 0

Steve11235
Steve11235

Reputation: 2923

I understand why you want to do this; however, Java simply does not provide that capability.

Upvotes: 1

Related Questions