java mandatory package declaration [duplicate]

五迷三道 提交于 2019-12-19 22:01:13

问题


In java, why is it mandatory for each class to declare the package it belongs to. I mean, package hierachy is already described/enforced using the folder structure of the file system. It looks to me that the line:

package com.mypackage;

As the first line of each class is somehow a redundant information. But I'm pretty sure there's a good reason for it to be there.


回答1:


I mean, package hierachy is already described/enforced using the folder structure of the file system.

Not necessarily. While it's certainly a good idea to organize your code that way, it's not a requirement. Also bear in mind that source code needn't be in a file system to start with.

Fundamentally, I think it's entirely reasonable to make the content of the source file the important thing. Heck, you could take it to the other extreme and assume the class being declared by the filename - that's not just a convention, but one which is explicitly valid (in the JLS) to be enforced by the compiler for public top-level classes.



来源:https://stackoverflow.com/questions/30598977/java-mandatory-package-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!