0

正如许多地方所说,一个类产生包私有访问级别,这意味着这样的类只能被同一个包的其他人访问。我对包了解不多,但我想知道您在文件开头添加“包 x”就足以提出我的问题。

我制作了一个带有类成分的文件。另一个文件包含

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

任何地方都没有包声明。尽管如此,我的程序还是成功编译了这两个文件,并且也这样运行。我错过了什么?烹饪课不应该看不到成分吗?

4

4 回答 4

1

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

于 2013-04-07T21:03:53.047 回答
1

类可以在没有导入语句的情况下看到同一目录中的其他类。包是组织代码的方法,本质上只是应用程序文件夹中的目录。所有类都可以在同一个类中看到其他类,而无需导入,这是在定义不同的包时,例如您的结构:

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

当然,您的成分文件将以开头,package utilities;如果您尝试从烹饪中访问它,您会收到错误消息,除非您import utilities.Cooking;在文件中有。包私有只是意味着包(或文件夹)之外的类无法查看或访问文件或其包私有属性。

于 2013-04-07T21:06:28.850 回答
1

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

于 2013-04-07T21:07:56.560 回答
1

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

于 2013-04-07T21:13:16.237 回答