Is really “No Public Class” reachable within its package?

Viewed 255

In "Think in Java", the author says:

You just leave the "public" keyword off the class, in which case it has package access. (That class can be used only within that package.)

To prove this, I create one public class and one no-public class:

package com.ciaoshen.thinkinjava.chapter7;
import java.util.*;

//My public class
public class PublicClass {
    //default constructor
    public PublicClass(){
        System.out.println("Hello, I am PublicClass.");
    }
}

//Non public class
//It should be package reachable
class PackageReachableClass {
    //default constructor
    PackageReachableClass(){
        System.out.println("Hi, I am PackageReachableClass.");
    }
}

But when I call them from another class in the same package:

public class InPackageClass {

/**
 *  MAIN
 *  @param args void
 */
public static void main(String[] args){
    //pubic class can be reached from anywhere
    PublicClass newPublicClass=new PublicClass();
    //non-public-class should be accessable in the same package
    PackageReachableClass newPackageReachableClass =new PackageReachableClass();
}
}

The system warning me: The no-public class should not be accessed from outside its own source file.

/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
        PackageReachableClass newPackageReachableClass =new PackageReachableClass();
        ^
/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
        PackageReachableClass newPackageReachableClass =new PackageReachableClass();
                                                            ^
2 warnings
Hello, I am PublicClass.
Hi, I am PackageReachableClass.

So here comes my question: Is the no-public class still package reachable? And why Java forbid us to call them from another file in the same package if this is totally legal?

1 Answers
Related