Reputation: 3
I have these two classes that I want to combine into a single file but i don't know how.
import java.util.LinkedList;
public class BFSolver{
public static boolean[][] didVisit;
public static LinkedList<Pair> expanded ;
public BFSolver() {
}
the other class looks something like this:
import java.util.LinkedList;
public class DFSolver{
public static boolean[][] didVisit;
public static LinkedList<Pair> expanded = new LinkedList<Pair>();
public DFSolver() {
}
when I put the import statments in one file and the classes declerations in the same file, I got the error 'Unchecked' inside the main class.
Upvotes: 0
Views: 120
Reputation: 30320
As others have stated, Java requires that only one public class can be in a single source file (unless the other is a static
inner class), and the file name needs to match the class name. Other languages like Scala relax this requirement.
More interesting though is why you feel you want to. It looks instead like you either want to combine the classes into a single inheritance tree (though they have to still be different files) because they share behavior or combine common code into a utility class that both classes can delegate to.
But in any event, you're stuck with two files if you have two public non-static
classes.
Upvotes: 0
Reputation: 10978
You cannot put more than one public class in the same java file, except for inner classes.
Upvotes: 1
Reputation: 106460
If the relationship between them can be described as "BFSolver
is a DFSolver
", then you can use inheritance to get around the issue instead. Both of these classes would have to be in different files, since they're both public.
public class DFSolver {
protected boolean[][] didVisit;
protected List<Pair> expanded;
public DFSolver() {
// impl
}
// further impl
}
public class BFSolver extends DFSolver {
public BFSolver() {
// impl
}
}
The advantage here is that you don't have to copy or rewrite code to BFSolver
; with the protected
visibility modifier, you can access those fields just the same.
Upvotes: 1