How to use a class from a parent directory in Java?

后端 未结 3 1806
感动是毒
感动是毒 2021-01-15 01:43

For example, I have a class called Foo inside Foo.java which will use a class called Bar inside ../Bar.java. Is there any

相关标签:
3条回答
  • 2021-01-15 02:13

    Assuming these are both your classes and belong to the same module, you should be using packages and both classes should exist in the same package hierarchy. Then it would work automatically.

    Packages would be something like com.company.application.module.Bar and com.company.application.module.subcomponent.Foo, for example. See more discussion on correct package naming:

    • Oracle.com: naming packages
    • wikipedia: package naming conventions

    You can also do javac -sourcepath path/to/src/solution/java;path/to/src/test/java to point to several locations explicitly (note that -classpath will also work, see this discussion about the differences).

    If we're talking about separate components that don't exist in the same module, you'd just use classpath to make the code aware of both (or preferrably some dependency mechanism like Maven that works out the stuff under the hood).

    0 讨论(0)
  • 2021-01-15 02:15

    Your classes have packages, which are mirrored in the directory structure. E.g. com/company/pk/Foo and com/company/Bar - then you can reference them using the import statement. If your classes are in different directories but don't declare a package, then you are doing it wrong.

    Read about packages

    0 讨论(0)
  • 2021-01-15 02:33

    Add your class to classpath..

    javac -cp "path to your Bar.class" Foo.java
    

    You will need to import that class in your Foo.java also.. Better use a package, and give the classpath till the directory containing your package..That way you will be able to give different namespaces to your classes..

    So, if your package is: - pkg1.pkg2.Barand you have saved your .java to a directory named Demo, then your classpath should contain path till Demo.. And your classes will actually be under two more directory pkg1/pkg2/Bar.class inside Demo directory..

    Demo+
        |
        +-- B.java (`Under package pkg1.pkg2)
        |
        +--pkg1+
        |      |
        |      +--pkg2+
        |             |
        |             +-- B.class
        |
        +-- A.java (`Under no package`) - Add - import pkg1.pkg2.B 
        |
        +-- A.class (javac -cp . A.java) - Will search the package pkg1.pkg2 in current directory
    

    Even though . is not needed there, you can replace it with any path, if your B.class is somewhere else..

    0 讨论(0)
提交回复
热议问题