Dustin's Pages

Wednesday, February 10, 2010

Java: "duplicate class" and Mismatched File Name Error

Developers who are new to Java can sometimes have trouble with class and package naming. In fact, the introductory Java forums are filled with threads starting with questions about these areas of Java. In this blog post, I look at some of these errors and some of the causes of these errors.

One of the more obvious errors occurs when a public Java class is named differently than the file that contains the class definition.

This is demonstrated in the next screen snapshot. In this example, a class was declared as public with the name Person, but was saved in a file called Person2.java. The error message is pretty explicit: "class Person is public, should be declared in a file named Person.java"

The "duplicate class" error can sometimes be a little more tricky to resolve. One situation in which this occurs is when two source code directories include the same class with the same package structure. This error looks like that shown in the next screen snapshot.

As the above screen snapshot indicates, the class dustin.examples.Person exists in both the src2 directory and (not shown here) in the src directory ("duplicate class: dustin.examples.Person"). Indeed, these are duplicate classes, at least in terms of package and class name.

The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names. This is shown in the next screen snapshot.

This screen snapshot demonstrates that the "duplicate error" occurs when the class names and declared package names match even if the source file exists in directories with different names (different even than the declared package structure). What this implies is that if a particular class was copied to another directory without changing the package statement and the new directory was in the source path for javac, the "duplicate class" error will occur.

Another interesting observation from the last example is that javac uses the package statement to decide where to build the .class file rather than using the source file's location in a directory structure.

In the blog post Java duplicate class error, Morgy describes a situation in which he ran into the "duplicate class" error message (he had neglected to place the class's package declaration at the top of the class).

Conclusion

In this post, I have attempted to show some common causes of errors that can be troublesome for those new to Java. Specifically, I have demonstrated some of the common causes of the "duplicate class" error and of the public class not matching its file name.