Is the use of Java's default package a bad pra

2019-01-01 03:03发布

问题:

Is the use of Java\'s default package a bad practice?

回答1:

Yes, it is. Ideally, package names should be globally unique, to avoid naming collisions. Using the default package breaks this convention. It\'s also impossible to import a class from the default package.

Why do unnamed packages exist at all, if it\'s such a bad idea? From the JLS §7.4.2:

Unnamed packages are provided by the Java platform principally for convenience when developing small or temporary applications or when just beginning development.



回答2:

There are problems on many different levels:

  • you can\'t import classes in the default package from classes that are not
  • you will get class loading problems if you try to resolve the default package in multiple artifacts
  • you can no longer use the default and protected scope like you normally can
  • there\'s no obvious distinction between your code and other code


回答3:

Yes it is. As other answers have stated, you can\'t load classes from the default package.

See SO answers:

How to import a class from default package
How to access java-classes in the default-package?

However, log4j requires that the configuration be located in the default package. This is the only thing that\'s reasonable to keep there.

Edit: As Sean Patrick Floyd and Michael have pointed out in the comments, you can put any configuration files into the default package. Thanks to both of you for pointing this out to me.



回答4:

Yes, it is. The problem is that it is not possible to import classes from the default package.



标签: java packages