Java引用同一目录中的类 [英] Java referencing a class in the same directory
问题描述
我用Java创建了一个 Pair
类(类似于c ++对),但在从另一个Java文件中引用它时遇到了麻烦.我正在处理Java文件,我们将其称为 fileA
,与 Pair.class在同一目录中.
另外,我在两个文件的顶部都写了 package当前目录
.
I created a Pair
class in Java (similar to the c++ pair) and am having trouble referencing it from a different java file. I am working inside a Java file, let's call it fileA
in the same directory as Pair.class.
Additionally, I have written package current-directory
at the top of both files.
但是,当我尝试 javac fileA
时,我所有的错误都是找不到符号
,并且小箭头指向了我的自定义 Pair
类型.
However, when I try javac fileA
all my errors are cannot find symbol
and the little arrow points to my custom Pair
type.
如何让Java编译器在 fileA
中看到 Pair.class
?
How do I get the java compiler to see Pair.class
inside of fileA
?
感谢所有帮助
推荐答案
Java由一些基本约定驱动,包括目录结构遵循包结构,并且java文件以它们定义的类命名.
Java is driven by some basic conventions, including that directory structure follows package structure, and java files are named after the classes they define.
您应该像这样将fileA定义为fileA.java内部的类:
You should have defined fileA as a class inside of fileA.java like so:
public class fileA {
public static void main(String[] args) {
Pair p = new Pair(0, 1);
System.out.println("a is "+p.a+" and b is "+p.b);
}
}
和相应的Pair类:
public class Pair {
public final int a;
public final int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
如果要从与两个java文件相同的目录中调用javac,则不应在顶部声明程序包,因为它们位于默认程序包"中.因此,上面的方法应该起作用.
If you are calling javac from within the same directory as both java files, you should not declare a package at the top, as they are within the 'default package'. As such, the above should work.
使用默认程序包提供了一些便利,但也提供了一些我将不详述的限制,但是现在您已经知道了默认程序包,可以查找它了.我建议使用软件包名称,就像添加名称一样简单:
Using the default package provides some convenience but also some restrictions which I won't elaborate on, but now that you know about the default package you can look it up. I recommend using package names, which is as simple as adding, as you did, something like:
package kugathasan;
每个文件开头的
.如果这样做,则应将两个文件都放在一个名为kugathasan的目录中,并从包含kugathasan的目录中调用javac.
at the beginning of each file. If you do this though, you should put both files in a directory called kugathasan and call javac from the directory containing kugathasan.
这篇关于Java引用同一目录中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!