IMK
IMK

Reputation: 718

Java Access Specifiers to access across packages without being public

I am building a java library which has different packages in it. Now the problem is, I want to access the java members (class, methods and fields) across the packages but those need not be exposed(from JAR file) to end level to client. For example

Class B in Package B should access the members of Class A in Package A

One possible scenario I found is declaring protected access specifier for the members of Class A and accessing those members in Class B by extending the Class A to Class B . My question is is this the only way I can achieve it in java?

What if I do not want to expose the Class A (as public) from JAR? In C# we use "internal" which will provide access within a CSharp library project but will not be exposed to end level from binaries(dll) or assembly files.

Upvotes: 0

Views: 103

Answers (1)

Jason C
Jason C

Reputation: 40315

No, there is nothing like this. You'll have to take a different approach. There are a ton of options, way too many to go over in a single answer, but off the top of my head just some basic ideas:

  • This could be a red flag indicating poor package organization. Consider organizing your packages into more functional groups.
  • This could be a red flag indicating some problematic design choices. Consider a more appropriate class and interface hierarchy.
  • Consider adding interfaces that expose what you need to expose.
  • Consider making said "internal" things public and safe to use externally.
  • Etc.

But you are going to have to do a bit of reorganization here. If you start adding various hacks to get around it it may suffice for now but you'll likely regret it later on. Always best to try and get the job done as correctly as possible the first time around.

Upvotes: 1

Related Questions