简体   繁体   English

在Java中的相同命名包中使用类

[英]Using Classes within the same named package in Java

I am trying to create two classes A and B that exist within a named package named components. 我正在尝试创建存在于名为组件的命名包中的两个类A和B。 A is a public class Window and B is a public class Door which contains an instance of A. The issue is that when compiling B using A是一个公共类Window而B是一个公共类Door ,它包含A的一个实例。问题是,使用

javac -classpath . Door.java

, B cannot find A. ,B找不到A。

I understand that I can make this code work in an unnamed default package with no import clauses however I want these files to exist within one named class so that they can be imported elsewhere. 我知道我可以使此代码在没有导入子句的未命名默认包中工作,但是我希望这些文件存在于一个命名类中,以便可以将它们导入其他位置。

I have demonstrated to myself that Door.java will compile if the package components; 我已经向自己证明,如果package components;Door.java将会编译package components; line is commented out from both files however I do want to have this as a package named components. 这两个文件中的注释行都被注释掉了,但是我确实希望将其作为一个名为components的软件包使用。

I have also tried using import components.Window; 我也尝试过使用import components.Window; within B but this doesn't work either. 在B中,但这也不起作用。

//class A
package components;
public class Window{
public void rollup(){}
public void rolldown(){}
}

//class B
package components;

public class Door{
    public Window window = new Window();
    public void open(){}
    public void close(){}
}

My current code shows this which demonstrates that package B currently cannot access package A. 我当前的代码显示了这一点,这表明程序包B当前无法访问程序包A。

Door.java:8: error: cannot find symbol
        Window window = new Window();
        ^

How do I fix this code to allow B to create an instance of A whilst being within the same named package? 如何修复此代码,以允许B在同一个命名包中创建A的实例?

Taking as reference the following structure 参考以下结构

/some/base/route/project/components
                          |- Window.java
                          |- Door.java

Then, running javac -classpath . components/Door.java 然后,运行javac -classpath . components/Door.java javac -classpath . components/Door.java (as well as javac components/Door.java ) from /some/base/route/project should work. /some/base/route/project javac -classpath . components/Door.java (以及javac components/Door.java )应该可以工作。

Notice that you need to run the command from 1 level up the directory that begins conforming the fully qualified package name for the classes. 请注意,您需要从1级最高的是开始为符合类的完全限定包名的目录中运行命令。 This mean, if you run the command from within /some/base/route/project/components it will not work. 这意味着,如果您从/some/base/route/project/components内部运行命令,它将无法正常工作。

Lastly, adding import components.Window; 最后,添加import components.Window; in Door class is useless because Window was already visible in Door since both classes are in the same package and Window is declared as public . 因为两个类都在同一个包中,并且Window声明为public ,所以Door类中的Window是无用的,因为Window已经在Door可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM