Skip to content
Advertisement

Package Visibility Issue in Java

DETAILS :

I am trying to build a java project from command line with the following directory structure :

proj/
    Makefile
    Main.java
    lexer
    tokens
    ast
    interpreter
    lib

QUESTION :

I assume that Main.java has access to all classes, enums, interfaces, and annotations of all the four folders. But, if I want to use the enum in tokens package, is there any way to do so ? By way, I mean what access specifiers should I use to fulfill my use case ?

LINKS which I used before asking this question :

-https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

-https://medium.com/virtuslab/on-the-missing-package-private-or-why-java-is-better-than-kotlin-in-this-regard-4a1c9ecbe40c#:~:text=The%20default%20access%20modifier%20in,classes%20in%20the%20same%20package.&text=It%20was%20hardly%20used%20and,fields%20when%20inheritance%20was%20needed.

-http://gauss.ececs.uc.edu/Courses/c694/lectures/Visibility/visibility.html

Thanks in advance.

EDIT : Main can import from packages and main is in default package.

Advertisement

Answer

Assuming you are using java8 and before:

  1. Main will not have access to all classes and enum by default
  2. Main will have access to classes and enums defined within Main.java
  3. A method in Main will have access to inner classes and enums
  4. Main will have access to classes and enums defined as public in other packages
  5. Main will have access to classes that it is extending in other packages(they should be atleast protected)

Similar access policy will be followed for other classes too. (Main has nothing special)

Please refer

  1. Tutorials
  2. Modifiers
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement