为什么java源文件需要包声明? [英] Why do java source files require package declarations?

查看:608
本文介绍了为什么java源文件需要包声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我无法理解java包结构,对我来说,java文件有一个package声明,然后也需要出现在一个与包名称匹配的目录中。例如,如果我有一个 MyClass.java 文件:

I think I am failing to understand java package structure, it seemed redundant to me that java files have a package declaration within, and then are also required to be present in a directory that matches the package name. For example, if I have a MyClass.java file:

package com.example;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}

然后我需要这个文件位于 com / example 相对于基本目录,我将从基本目录执行 java com.example.MyClass 运行它。

Then I would be required to have this file located in com/example, relative to the base directory, and I would execute java com.example.MyClass from the base directory to run it.

为什么编译器不能通过查看目录结构来推断包名称?例如,如果我从基本目录 javac com\example\MyClass.java 编译文件,我不明白为什么MyClass.java不会隐式属性到 com.example 包。

Why wouldn't the compiler be able to infer the package name by looking at the directory structure? For example, if I compiled the file from the base directory javac com\example\MyClass.java, I am not understanding why the MyClass.java wouldn't implicity belong to the com.example package.

我理解有一个默认包,但似乎包在源文件中声明是多余的信息?

I understand there is a default package, but it still seems that the package declaration in the source file is redundant information?

推荐答案

em>声明包的名称...在默认包的情况下。

As you (implicitly) acknowledged, you are not required to declare the name of a package ... in the case if the default package.

忽略那个quibble ...这个看起来冗余的原因是没有对于 package 声明的要求,Java源代码的含义将是不明确的。例如,路径名为/home/steve/project/src/com/example/Main.java的源文件可以有7个不同的完全限定名称,具体取决于编译代码的方式。很可能,只有其中一个将是正确的一个。但是你不能通过查看(只是)源代码文件来判断哪个是正确的。

Ignoring that quibble ... the reason for this seeming redundancy is that without the requirement for a package declaration, the meaning of Java source code would be ambiguous. For example, a source file whose pathname was "/home/steve/project/src/com/example/Main.java" could have 7 different fully qualified names ... depending on how you compiled the code. Most likely, only one of those will be the "correct" one. But you wouldn't be able to tell which one is correct by looking at (just) the source code file.

还应注意,Java语言规范而不是 您需要根据包来组织源代码树。这是一个(大)Java编译器家族的一个要求,但是可以编写一个不需要这个的一致性编译器。在这种情况下,声明不会重复。

It should also be noted that the Java language specification does not require you to organize the source code tree according to the packages. That is a requirement of a (large) family of Java compilers, but a conformant compiler could be written that did not require this. In that eventuality, the package declaration would not be duplicative.

这篇关于为什么java源文件需要包声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆