Using Classes within the same named package in Java

Didgeridude :

I am trying to create two classes A and B that exist within a named package named components. 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

javac -classpath . Door.java

, B cannot find 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; line is commented out from both files however I do want to have this as a package named components.

I have also tried using import components.Window; within B but this doesn't work either.

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

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?

lealceldeiro :

Taking as reference the following structure

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

Then, running javac -classpath . components/Door.java (as well as javac components/Door.java) from /some/base/route/project should work.

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. This mean, if you run the command from within /some/base/route/project/components it will not work.

Lastly, adding 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83265&siteId=1