1
votes

In The Java Programming Language by James Gosling its specified that

"As with other anonymous inner classes, the enum constant class body can define arbitrary instance fields, and methods, but it can't declare static members or define constructors. Also note that because enum constants are implicitly static fields, these anonymous inner classes have no enclosing instance."

i tried to do that in following code and get error

"The field pieceType cannot be declared static; static fields can only be declared in static or top level types" (what does it mean)

package com.example;


enum ChessPiece{
    PAWN{
        @Override
        void pieceName(String name) {
            // TODO Auto-generated method stub
            System.out.println("PAWN");
        }
    },
    ROOK{

        @Override
        void pieceName(String name) {
            // TODO Auto-generated method stub
            System.out.println("ROOK");
        }
    },
    QUEEN{
        static String pieceType = "QUEEN"; // ERROR
        @Override
        void pieceName(String name) {
            // TODO Auto-generated method stub
            System.out.println("QUEEN");
        }
    };

    abstract void pieceName(String name);

}

why is it so ?

2
Because the spec says so... But since there can only ever be one instance of the QUEEN class it makes no difference, just declare the field as non-static instead.Ian Roberts
i just added that field to check above statement given by james goosling and for that i got an error.want to knw the clear meaning of that statement.Prateek

2 Answers

0
votes

you can only declare static variables in classes.

0
votes

Well, let's look at what's really going on here.

QUEEN{
    static String pieceType = "QUEEN"; // ERROR
    @Override
    void pieceName(String name) {
        // TODO Auto-generated method stub
        System.out.println("QUEEN");
    }
}

It might not be immediately obvious, but you've declared an inner class here. This necessarily follows from the fact that you're implementing an abstract method, and can be verified easily enough:

System.out.println(ChessPiece.class == ChessPiece.QUEEN.getClass());

And the spec says that non-static inner classes [2] can't declare static members. I don't believe there is any big theoretical reason for that [1], aside from being somewhat conceptually weird, but it's how it is.

Put another way, you should see the same error on something like this:

class Foo {
    static final String TOP_LEVEL = "ok";
    static class Bar {
        static final String NESTED_STATIC = "ok";
    }
    class Bar {
        static final String NESTED_NOT_STATIC = "error";
    }
}

[1] Someone with better understanding of Java plumbing should feel free to correct this.

[2] I guess the difference between static and non-static inner classes can be somewhat confusing itself. I suggest looking into it and asking a follow-up question if needed.