Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java access modifier properly in library development

I'm developing a library which the other programmer will import and use it for their purposes.

I'm confused about the objective of Java access modifier.

The problem is that I have classes below

  • ClassA in package org.mylibrary
  • ClassB in package org.mylibrary.internal

ClassA needs to resolve ClassB so ClassB need to be public class.

However, from library user view, I don't intend ClassB to be visible outside my library. Because it shouldn't be and don't need to be initiated by the user.

I think of moving ClassB to package org.mylibrary and make it package-private class.

If I move it to the same package, it would be a mess and difficult to organize because I have many classes in this scenario so there will be many .java files in a big one package.

Normally I put the classes in packages grouped by category or layer and I think it's easy to organize.

How do I do this? How do people handle this problem?

like image 234
teerapap Avatar asked Sep 16 '10 09:09

teerapap


People also ask

How are access modifiers used in Java?

In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For example, class Animal { public void method1() {...} private void method2() {...} }

What is the correct order for the access modifiers in Java?

There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer).

What are the 4 access modifiers in Java?

Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors in a class. The four access modifiers in Java are public, protected, default, and private.

How access modifiers are useful in encapsulation in Java?

Encapsulation in Java would not be as effective as it is today without access modifiers. Access modifiers allow us to decide how parts of our classes can be accessed by other classes in other parts of our program. If we want a field or method to be accessible from anywhere, by any class, we can mark it as public.


1 Answers

It is difficult to give concrete advice since you give so little info about the roles of and relationship between ClassA and ClassB. However, one general solution (which is almost always used as part of eliminating dependencies) is to hide ClassB behind an interface. Then ClassA uses only that interface, so it is not anymore directly dependent on ClassB. ClassB can be made package private, its instances produced by e.g. a factory, or dependency injected into ClassA.

like image 156
Péter Török Avatar answered Oct 25 '22 04:10

Péter Török