Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Access to static fields in enum constructor is forbidden by the compiler. Below source code works:). It uses static field:

public enum TrickyEnum
{
    TrickyEnum1, TrickyEnum2;

    static int count;

    TrickyEnum()
    {
        incrementCount();
    }

    private static void incrementCount()
    {
        count++;
    }

    public static void main(String... args)
    {
        System.out.println("Count: " + count);
    }
}

Output: Count: 2.

This does not work. Difference is very small:

public enum TrickyEnum
{
    TrickyEnum1, TrickyEnum2;

    static int count;

    TrickyEnum()
    {
        count++; //compiler error
    }

    public static void main(String... args)
    {
        System.out.println("Count: " + count);
    }
}

As I searched internet, usually people answered the problem is connected with order of initializing static fields.But first example works, so why do java developers forbid second example? It should also work.

share|improve this question
 
Why would you use this counter ? –  Christophe Roussy 19 hours ago
4  
It is only example for me to better know the java. Correct way is incremenenting static counter in static block or do not create this. It is redundant, enum elements can be counted, but I want to understand what is going on it this code. –  Pawel 19 hours ago
 
This is an interesting case indeed. –  Christophe Roussy 19 hours ago
add comment

1 Answer

up vote 17 down vote accepted

The compiler allows a call to a static function, because it is not smart enough to prohibit it: the legitimacy of the call cannot be deduced without looking into the body of the incrementCount method.

The reason this is prohibited becomes clear when you run the following code:

enum TrickyEnum
{
    TrickyEnum1, TrickyEnum2;

    static int count = 123; // Added an initial value

    TrickyEnum()
    {
        incrementCount();
    }

    private static void incrementCount()
    {
        count++;
        System.out.println("Count: " + count);
    }

    public static void showCount()
    {
        System.out.println("Count: " + count);
    }
}

public static void main (String[] args) throws java.lang.Exception
{
    TrickyEnum te = TrickyEnum.TrickyEnum1;
    TrickyEnum.showCount();
}

This prints

1
2
123

which is extremely confusing to a programmer reading your code: essentially, incrementCount does its modifications to the static field before it has been initialized.

Here is a demo of this code on ideone.

share|improve this answer
1  
As I thought. I wanted to be sure :). Thanks. –  Pawel 19 hours ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.