Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java packages and classes

I'm building a very simple library in Java, which will be packaged in a single Jar. It should only expose one class: World. The World class uses the subclasses of the Block class, which is in the same package (com.yannbane.a), and doesn't provide a lot of functionality itself, but needs to be extended. I planned to create another package, com.yannbane.a.blocks, which would have all the block types (subclasses).

The directory/package structure should, therefor, look like this:

com/
    yannbane/
        a/
            World.java
            Block.java

            blocks/
                Brick.java
                Stone.java

However, in order for the subclasses of Block to actually extend the Block class, I needed to make the Block class public. This destroys my goal of having the Jar file only expose a single class, World. I also need to make the subclasses public so the World could use them.

How can I retain this package and directory structure but still have my Jar only expose the World class, not other classes?

like image 682
corazza Avatar asked Oct 06 '22 06:10

corazza


2 Answers

If this is a matter of encapsulation, and all you want to expose to the world is the "World" class, then it does not matter if the unexposed classes are located in the same package or if they are inner classes in the same package.

At any rate, they will not be accessible to the users of your API. I believe encapsulation is more important here than the "logical" organization that you want to give your files. Because if you locate all your classes in the same package, then you will not have these problems and you will achieve the level of encapsulation that you are seeking. Perhaps what Java is telling you is that these classes are so inherently related that you should place them all in the same package.

like image 166
Edwin Dalorzo Avatar answered Oct 09 '22 16:10

Edwin Dalorzo


Make the classes public but their constructors protected.

You still technically expose the classes - other packages are aware of them - but no other packages can instantiate those objects.

Even though the Block subclasses are in a different package from Block (com.yannbane.a and com.yannbane.blocks) they will be able to invoke the protected parent constructor, because protected members are accessible from the same package or from an inheriting object.

like image 43
Richard JP Le Guen Avatar answered Oct 09 '22 17:10

Richard JP Le Guen