Java – Is Default Package included in the Package Level Access

java

I would like to know how the default package is defined in Java.I know how public and private access is defined but I don't know whether there is any default package access that is defined in package level access in java.

I'm asking this question because when I compile java file containing two classes since no modifier is given for classes,java compiler would give package level access as the default access modifier for the classes.Since no package is defined,java compiler would use the default package but I couldn't get whether the default package is included in package level access in java.Could anyone help me.

Best Answer

The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.

It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.

For example I have 2 java files:

public class A{
    public static void foo(){System.out.println("fooCalled");}
}

and

package com.example;

public class B{
    public static void main(String[] arg){
        A.foo();//won't compile
    }

}

Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.

If you ever start making larger programs then you should put all your code in packages. It allows you to segregate your code in a way that makes sense.

The accepted practice is to name you package after a domain the program is part of like com.example