mizech mizech - 17 days ago 5
Java Question

Java: What would be the consequence of leaving the package statement out?

I'm new to Java and still have a hard time to fully understand the concept of packages and namespaces.

Obviously have classes to be placed in a directory which has the same name as their package. If I have nested packages then the directory path have to map the used package string. Only that the directory path uses Slash, respectively back-slashes for to separate the levels while the package string uses dots.

Now: If I have to reproduce the package string with directories anyway ... Why can't Java figure out itself to which package a class belongs? Why is the additional package statement needed?

I ask myself: It should be obvious anyway because of the rule that the containing directory has always the name of the package name. ??

Moreover:
What happens if I have nested packages and I DO NOT write a package statement in one of the contained classes?

Answer

Why can't Java figure out itself to which package a class belongs? Why is the additional package statement needed?

packages are required to resolve the class name conflicts and load the correct class by the class loaders (inside JVM) into the memory.

Assume that you have created two classes with same name as Utils class (one Utils class for Maths and one Utils for Physics), then JVM during class loading time must know & resolve which of this Utils class need to be loaded/required. That's where packages will come to the rescue and you can define com.maths.utils and com.physics.utils packages and add the Utils class into the right package so that we can use it later in any other class by using import keyword to specify which Utils we are referring to i.e., in short, packages provide the complete full name to the class file.

  • Multiple classes (related to same functionality) can be grouped as packages.
  • Multiple packages (related to same functionality) can be grouped as JAR file.

What happens if I have nested packages and I DO NOT write a package statement in one of the contained classes?

If you have nested packages and if you dont write the package name using the package keyword at the top of the class, then the code will not compile.

I suggest you read here more on this.