简体   繁体   中英

Why enum constant class body can define arbitrary instance fields, and methods, but it can't declare static members or define constructors

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 ?

您只能在类中声明静态变量。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM