Is "No Open Class" Really Available As Part Of Its Package?

In Think in Java, the author says:

You simply leave the keyword "public" outside the class, in which case it has access to the packages . (This class can only be used inside this package.)

To prove this, I create one public class and one non-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 one 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 warns me: An open class should not be accessible 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 is my question: is access to the package available without public access? And why does Java forbid us to call them from another file in the same package, if this is completely legal?

+6
source share
1 answer

This is just a warning that you have defined a helper class.

helper class PackageReachableClass in PublicClass.java

This means that you have one Java file with 2 classes, which is against Java Code Conventions . (My emphasis).

Each Java source file contains one public class or interface. When private classes and private interfaces are associated with an open class, you can put them in the same source file as the public class. The public class must be the first class or interface in the file.

To test your private package classes correctly, split the two classes into separate files based on their class name, i.e. PublicClass.java and PackageReachableClass.java .

+1
source

All Articles