'Java cannot find enum in the other class

I wrote down a Enum class which could successfully compile, and then whenever I use the Enum class as a type of variable in the other class of the same package, the "cannot find symbol" would occur when compiling.

Here is the code for Enum:

package cards;

public enum CardType {
NIGHTMUSHROOM,DAYMUSHROOM,CIDER,BUTTER,PAN,BASKET,STICK
> }

And then I use the Enum in another class, I tried to import while the two pieces of code are in the same package so there is no use for the error.

package cards;

//import static cards.CardType;

public class Card{
    protected CardType type;
    protected String cardName;

    public Card(CardType newType,String newName){
        this.type = newType;
        this.cardName = newName;
    }

    public CardType getType(){
        return this.type;
    }

    public String getName(){
        return this.cardName;
    }
}

However when I compile Card class, I report the error message like below Cannot find symbol of enum

I have looked at some of the questions about enum in the forum while they couldn't make sense for my code.



Solution 1:[1]

The CardType class's full name is cards.CardType (it's the package name, plus a dot, plus the classname). Hence, when javac is attempting to compile Card.java, it looks for the class cards.CardType. To find it, it scans the classpath roots for the path /cards/CardType.class.

It can't find this file, hence, error.

The 'root' that you need to make this work is the parent directory of whereever Card.java lives. After all, if you start at that path and 'dir' into cards and then look for CardType.class, that'll work. It's generally a good idea to stay in this 'root' instead of CDing into subdirs from there.

Hence:

cd /home/tianyue/projects/myawesomeproject
ls;     -- prints: "cards"
ls cards;   -- prints: "CardType.java Card.java"
javac cards/CardType.java
javac cards/Card.java

Will work fine unless you've been messing with settings and removed . as default path. You can always forcibly add it - javac -classpath . cards/Card.java instead. Or, much simpler:

javac cards/*.java

Note that most folks will use a build system such as gradle or maven, or an IDE, to take care of building projects. Once you involve multiple packages and dependencies, trying to command-line your way through a compilation process with just javac invokes gets real tedious.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rzwitserloot