Java-Hiding Classes

Hiding Classes

When we import a package within a program, only the classes declared as public in that package will be made accessible within this program. In other words, the classes not declared as public in that package will not be accessible within this program.

We shall profitably make use of the above fact. Sometimes, we may wish that certain classes in a package should not be made accessible to the importing program. In such cases, we need not declare those classes as public. When we do so, those classes will be hidden from being accessed by the importing class. Here is an example :

 

Here, the class DataClass which is not declared public is hidden from outside of the package mypack. This class can be seen and used only by other classes in the same package. Note that a Java source file should contain only one public class and may include any number of non-public classes.

Program

final

Java compiler would generate an error message for the code DataClass da = new DataClass(); because the class DataClass, which has not been declared public, is not imported and therefore not available for creating its objects.

Leave a Comment