1
votes

I have started learning packages in java.I learned about the import keyword.Now my doubt is whether it is .class file or a .java file that is being imported while we import any class in java.

2
I don't think it's either one of those. It just loads those classes into memory. - Steven Lemmens
Do you mean that classes are loaded at compile time? - Shashikanth Reddy
write a java class dont compile it. and try to use it in another class using import. you will get the answer - Mandar Dharurkar
This idea really worked.Thanks to @MandarDharurkar - Shashikanth Reddy
Great!thanks @shashikant - Mandar Dharurkar

2 Answers

3
votes

An import in a Java files does nothing more than allowing you to refer to a class by it's short name rather than it's fully qualified name.

So if you use a class named some.package.CoolClass then you can either use that full name everywhere in your code or just put import some.package.CoolClass; on the top and call it just CoolClass in your code.

The compiler needs to be able to load the class the you are using (whether or not you imported it) and that means it either needs to find the .class file of that class or also compile the .java file at the same time (i.e. if you have two classes A and B and compile them both at the same time then each can reference the other, even if there technically aren't any class files of them around at that time).

At runtime (i.e. when you actually execute your code) you'll need the .class files of each class you use on your classpath. (.java files are not used at runtime). Again, it doesn't matter if you used an import to use the short name or used the fully qualified name in your code.

2
votes

Does the compiler use .class or .java files for an import?

Answer: .class files, possibly compiling .java files.

This works, even in the following case (when there are no .class files):

// p/a/A.java
package p.a;
import p.b.B;
public class A {
    public static final A DEFAULT_A = new B();
}

// p/b/B.java
package p.b;
import p.a.A;
public class B extends A {
}

The reason that this (a cyclic dependency) can be dealt with, is that .class files are comparable with .obj / .o object files: there is symbolic information (class and method names) in the .class files. And just as the object files are linked with a linker to an executable or library, the java class loader resolves everything.