开发者

How to call Java package

开发者_运维知识库

I have two classes which is in different packages (folder). How can I call variable from FirstClass.java to see the variable in the SecondClass.java. If all variables is public.

first class is in -> C:\workspace\First\FirstClass.java

second class is in -> C:\workspace\Second\SecondClass.java


I think that you mean that the 2 classes are in different eclipse (I assume you are using eclipse) projects.
In you Project->Properties->BuildPath add a reference from one project to the other
Then you will be able to use the classes


Beware that packages are not folders. Packages are sort of "virtual" folders, corresponding to a certain path. These packages may be located at very different places on your file system, and even in different sorts of files (like Java ARchive files, named *.jar for example).

In your question, it is not clear what is the classpath of your project. I'll assume that the root of your project is C:/workspace.

So, FirstClass is in the package First. Second class is in the package Second.

(By the way, you should stick to the conventions of java, which say that a package has always lowercase characters.)

In that case, in order to access you'll have to put:

package First;
import Second.SecondClass; // <- Here is the import.
class First{
  // ...
}

at the beginning of your FirstClass.java file. SecondClass has to be defined as a public class to do so.

package Second;

public class SecondClass{
  // ...
}

If you forget the 'public' keyword, your class is only visible for classes in the same package.


If the variables reside as public fields in the classes, there should be no problem accessing the fields from outside code, despite the different packages.

...
package first;
public class First {
  public Integer var;
  ...
}

...
package second;
public class Second {
  public Integer var;

  public void test(Second other) {
    System.out.println(other.var);
  }
...

}

If you have problems, maybe you have them in different projects, as your paths suggest? Java-code only spans the same project on Eclipse.


For demonstration purposes, this code should work:

Files in first/First.java and second/Second.java

package first;

public class First {
    public int x;
}


//////////////////////////////////////

package second;

import first.First;

public class Second {
    private int y = new First().x;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜