java 声明包,为什么java源文件需要包声明?

Java的包结构设计要求源文件中的包声明与文件所在的目录结构匹配,这看似冗余,但实际上是为了避免编译时的歧义。没有这个规定,同一个源文件可能有多种全限定名,导致编译困难。虽然Java规范不要求按包结构组织源代码,但大多数编译器都这样要求。因此,包声明提供了清晰的命名空间,确保代码的唯一性和可读性。
摘要由CSDN通过智能技术生成

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");

}

}

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.

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?

解决方案

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

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值