“Cannot Find Symbol” compile error

2020-07-11 08:01发布

问题:

My coding experience has only gone back a few years, so this question should be easy enough to answer.

I have written two interfaces: Class and Game. Interface CLASS is supposed to extend interface GAME.

Here are the two interface sources:

package Impl;

public interface Game
{
    //METHODS AND VARS
}


package Impl;    

public interface Class extends Game
{
    //METHODS AND VARS
}

Now, when I try to compile the second interface, I get the following error

class.java:4: cannot find symbol
symbol: class Game
public interface Class extends Game
                               ^

My Game class is compiled and the class file is in the same directory as both java files. I have not been able to find a solution. Does anyone have any ideas?

回答1:

Class names are case sensitive. It is possible that you have created an interface called game, but you refer to it in your Class interface declaration as Game, which the compiler cannot find.

However, there is another chance that you are compiling from within your Impl package. To do this, you will need to reference your classpath such that the compiler can find classes from the base of the package structure. You can add a -classpath .. arg to your javac before the class name:

javac -classpath .. Class.java

Alternatively, you can do what is more common, compiling from the root of your package structure. To do so, you will need to specify the path to your Class file:

javac Impl\Class.java

you can always add a -classpath . to be clear.



回答2:

You need to read up on how Java classpaths work and how you should organize your source code. Basically, your problem is that when javac compiler compiles "Class.java", it does not expect to find "Game.class" in the current directory. It (probably) is looking for it in "Impl/Game.class".

The IBM "Managing the Java classpath" page provides an in-depth discussion of how to set your classpath and how java utilities (e.g. java and javac) use it to find class files. The Oracle "Setting the Classpath" page provides more information more succinctly ... but you need to read it carefully.

By the way, you've got some style atrocities in your code:

  • Java package names should be in all lower-case.
  • Calling a class Class is a bad idea, because this collides with the class called java.lang.Class which is imported by default.