简体   繁体   中英

Java default class access of package-private works like public

As stated in many places, a class yields a package-private access level, which means such a class can only be accessed by others is the same package. I don't know many things about packages, but I suppose knowing you add "package x" at the start of a file is enough knowledge to pose my question.

I've made a file with a class ingredient. Another file contains

public class cooking{ 
    public static void main(String[] args) {.....

There's no package declaration anywhere. Still, my program compiles the two files successfully, and also runs so. What am I missing? Shouldn't the cooking class NOT be able to see ingredient?

您的IDE(如netbeans或eclipse)将编译代码,因为这两个类都在同一个项目中,并且它“知道”您的意思是该类。

Classes can see other classes in the same directory without import statements. Packages are ways to to organize your code and essentially just directories in the application folder. All classes can see other classes within the same class without the need for importing, it's when different packages are defined such as your structure being:

src
 |
 +- Cooking.java
 |
 +- utilities
     |
     +- Ingredient.java

Of course your Ingredient file would be prefaced with package utilities; and if you tried to access it from cooking you'd get an error unless you had import utilities.Cooking; in the file. Package-private simply means that classes outside of the package (or folder) cannot see or access the file or it's Package-private properties.

if you do not add a package statement to java classes, then those classes are in the same package = the so-called "default" package. and therefore those classes have access to each other no matter if you define the classes as public or not.

public class A

= this class A is visible in all packages

class B

= this class B is visible only by classes in the same package as B

As laid out in the Java Language specification your classes are part of an (the) unnamed package, that's why they can see each other.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.4.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM