Search code examples
javaclassimportjavac

How to import java package


I have two folders a and b:

  • in a I have a ClassA.java,
  • in b I have a ClassB.java.

I want to ClassB.java import ClassA.java. How could I do that?

If I just write import a.ClassA, I cannot compile it.


Solution

  • Based on your comments it looks like you added package declarations in your classes like

    package a;
    public class ClassA{
        //...       
    }
    

    and based on your question you claimed that you also included import a.ClassA in ClassB like

    package b;
    import a.ClassA;
    public class ClassB{
        //...       
    }
    

    So to compile your ClassB from b directory you need to include in your command localization of other packages you are going to use, in this case localization of directory holding directory a. You do it by setting -classpath parameter (or shorter -cp).

    So if you are in folder b you can do it via

    javac -cp .. ClassB.java
    

    where .. means parent directory (the one holding both a and b).

    To run your code you also need to point location of directory holding additional packages used by your application. So you would need to use

    java -cp .. b.ClassB