Search code examples
javaimportjar

Does jar file not contain imported packages and classes?


I tried a simple A package B package example.

Package structure is like this -

---A
     |---a.class
---B
     |---b.class

a.class imports package B and class b.

Then I created a jar file with the following command -

jar -cvf a.jar A

Then I displayed the contents of the jar file using "jar -tf a.jar" command, and I see the following -

META-INF/
META-INF/MANIFEST.MF
A/
A/a.class

How come B/b.class is not a part of the jar file when A/a.class imports it?

Also how does A/a.class run correctly with B/b.class being a part of it?

java -cp ./A.jar A.a

Solution

  • The import statement allows you to refer to a class that's in another package by its short name; it does nothing else. imports aren't even carried over to the compiled .class file; all references are replaced by fully-qualified names.