简体   繁体   中英

Controlling Class Visibility in Java

My project has currently following package structure.

在此处输入图片说明

Here I have added a package name utils and defined all utility classes related to this module inside it. Those have been used by other packages (ie impl , internal ), and because of that I have made classes and methods in util package public .

Because, it is public, not only classes in this module, classes in other modules can also access this and when I am coding using my IDE they are shown as coding suggestions.

I went through few research papers which describe how this can reduce the usability of the API and give a bad experience to developers who involve in the development [ref1 , ref2] .

I understand that java does not allow me to make classes inside util accessible to impl and internal packages and not to others.

Is it correct to put my utility classes to a package 'util'? Or should I put all classes that communicate with each other to the same package?

Util classes are fine. Util classes are functionality that is used multiple places in a project but doesn't really belong to a specific class.

In a perfect world of OOP there wouldn't be any util classes, but it is however considered a good practice to create util classes if they do not belong to a specific class.

Your options for access modifiers are listed here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

There is one way to achieve what you you want, it is however concidered a very bad practice. You can change your access modifiers of util classes to protected . This will make your util classes accessible from subclasses and packages. So if a class needs access to one of the util classes, then it has to extend this util class and thereby become a subclass. I cannot stress it enought, this is a very bad practice.

You are correct, something marked public becomes usable in any other package. In contrast to other languages, Java doesn't provide any control beyond that.

A simple workaround: it might be helpful to have one special package containing those public things that should be available to your external users.

Meaning: create something like com.whatever.product.api - and instruct your users that they are fine to use everything from there - but nothing else.

In other words: you make all those things public that you need to public ; but you collect those things in a special place that you allow to be used by others.

It is worth mentioning though that Java9 will introduce the concept of modules , those allow you to define which of your packages should be public to users of your module. In that sense, java 9 modules allow you to distinguish between "internal" and "external" public .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM