问题
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.
However, when I try javac fileA
all my errors are cannot find symbol
and the little arrow points to my custom Pair
type.
How do I get the java compiler to see Pair.class
inside of fileA
?
Thanks for all the help
回答1:
Java is driven by some basic conventions, including that directory structure follows package structure, and java files are named after the classes they define.
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);
}
}
and a corresponding Pair class:
public class Pair {
public final int a;
public final int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
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;
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.
回答2:
It is a package structure issue. You may understand by seeing this screenshot how they look in my IDE and in folder.
And in the folder, they look like this.
And in code, they have this package.
package com.jini;
Hope you get the idea how this works.
回答3:
technocrat's comment is correct.
In Java, you don't normally work directly with the .class files when developing your application. You work with the .java files. The packages that you create in your IDE should contain your .java files.
So instead of putting Pair.class inside the same package directory as fileA.java, put Pair.java in it. You should then have a directory/package that contains both fileA.java and Pair.java
回答4:
If they are in the same directory, You need to compile both classes at the same sentence;
javac fileA.java pair.java
来源:https://stackoverflow.com/questions/21669272/java-referencing-a-class-in-the-same-directory