views:

54

answers:

2

In the code example below, I'm trying to test the value of an enum in the parent class. The error I get is "p.theEnum cannot be resolved or is not a field.", but it's the exact same code I use in the parent class to test the value (without the p. obviously).

Where am I going wrong? :)

public class theParent {
    protected static enum theEnum { VAL1, VAL2, VAL3 };
    private theEnum enumValue = theEnum.VAL1;

    theParent() { this.theChild = new theChild(this); this.theChild.start(); }

    class theChild {
        private parentReference p;

        public theChild (theParent parent) { this.p = parent; }

        public void run() {
            // How do I access theEnum here?
            if (p.enumValue == p.theEnum.VAL1) { }
        }
    }
}
+3  A: 

Just change it to:

if (p.enumValue == theEnum.VAL1) { }

There's no need to qualify it.

(Just as an FYI, it would help if you'd make samples like this compile apart from the problem area - I had to make quite a few changes aside from the one above before I could make it compile.)

Jon Skeet
Ah cheers. The problem I ran up against there was that theEnum is actually called State, and it was trying to use Thread.State, hence the presence of p.theEnum instead of just theEnum :)Also, sorry about the lack of compilation. I only half-know Java (I'm a PHP guy learning it) so I just did the best I could in a textarea :P What did I miss?
JoeC
@JoeC: It's best to come up with short but complete examples in an IDE, so you can check them. In this case, you're calling `start` on `theChild` which is invalid, and you've got a variable of type `parentReference` rather than `theParent`. Also you haven't declared a field called `theChild` but you assign to it in the parent constructor. I think there may have been others too - not sure. Also, I'd suggest using names which reflect Java naming conventions, as that makes oddities stand out more.
Jon Skeet
+1  A: 

Since you are using the class from within theParent, you don't actually need to qualify it.

But, even though you don't need to qualify, it should still be possible to qualify.

The reason you get the error is that theEnum is a static inner class, but the p.theEnum qualifier indicates a non-static inner class which requires the instnace p as part of instantiation. Here, the enum is declared static, so the correct way to qualify it is theParent.theEnum.

mdma
Already answered and voted for most useful (fastest) but the bit on the correct way to quantify it was very useful, thanks :)
JoeC