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
A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.
To import java package into a class, we need to use java import keyword which is used to access package and its classes into the java program. Use import to access built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With