Reputation: 1696
Suppose I have a class that contains an enum in Java. Is it possible to access methods from the class that the enum is contained in? As an example:
public class Foo {
private string getClassVal() { return "42"; }
public string getOtherClassVal() { return "TheAnswer"; }
public enum Things {
ONE("One"),
TWO("Two"),
THREE("Three");
private String _val;
private Things(String val) { _val = val; }
// This method is the problem
public String getSomeVal() {
return _val + this.getClassVal();
}
// And this one doesn't work either
public String getSomeOtherVal() {
return _val + this.getOtherClassVal();
}
}
I know the enum methods above with comments do not work and result in errors, because of the context that this
is in. What I'm looking for is something where I can access the "outer" class methods from within the enum. Or is this even the correct approach?
Is something like this possible? Or are enums locked up to outside methods, even within a class?
Upvotes: 3
Views: 782
Reputation: 65851
No.
Because enum
s are always static
and therefore have no enclosing instance.
Obviously they CAN access public static
methods of the enclosing class.
Upvotes: 5