Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static context in enum definition

Tags:

java

enums

javac

The syntax sugar provided by Java's enum facility can sometimes be a little confusing. Consider this example, which does not compile:

public enum TestEnum {

    FOO("foo") {
        public void foo() {
            helper();  // <- compiler error
        }
    };

    String name;
    TestEnum(String name) {
        this.name = name;
    }

    public abstract void foo();

    private void helper(){
        // do stuff (using this.name, so must not be static)
    }
}

Can anyone explain why the compiler says

Non-static method 'helper()' cannot be referenced from a static context

How exactly is this context static?

You can make this compile by changing the call to this.helper() (here is one confusing point: if we really are in a "static context" like the compiler suggests, how can "this" work?) or by increasing the visibility of helper() to default level. Which would you prefer? Also, feel free to suggest a better question title :-)

Edit: I found some discussion about this - but no real answers. My colleague thinks the fact that that this.helper() works is actually a compiler bug. And indeed with newer Java versions it seems not to work (although super.helper() does): "cannot find symbol helper()". (Although there's something odd going on: after trying with different Java versions I can't get this.helper() to compile again with any of them...)

like image 894
Jonik Avatar asked Feb 24 '09 11:02

Jonik


People also ask

Is enum a static context?

Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.

Can an enum be static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Are enums static by default?

Yes, enums are effectively static.

Can we define enum inside interface?

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.


1 Answers

The error message is misleading, just make helper protected and it will work.

protected void helper(){
    // can be called from subclasses (such as FOO) since it is not private
}
like image 119
akuhn Avatar answered Nov 07 '22 14:11

akuhn