Search code examples
javajava-package

Whether we import source code or byte code of a class when importing that class in java?


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.


Solution

  • 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.