Reputation: 2146
Could anyone explain why
public class Testabut{
enum ThreeColors{RED, BLUE, green;
public void woowoo(){
System.out.println("woo");}
}
ThreeColors color;
class Innerclass{
Innerclass(){
color.woowoo();
}
}
generates a null pointer exception at the invocation of woowoo() ? The instance of color should be reachable, no?
Upvotes: 3
Views: 12111
Reputation: 22710
Because color
is not initialized and it's default value is null
.
Initialize it like
ThreeColors color = ThreeColors.RED; //Or any other value
Upvotes: 5
Reputation: 6032
You have to initialize color
. Try color = ThreeColors.RED;
or color = ThreeColors.BLUE;
or color = ThreeColors.green;
!
Upvotes: 1
Reputation: 42176
Your color
variable is null. You have to initialize it to use it.
Upvotes: 4
Reputation: 424993
All instance variables are initialized with a value. If you do not provide a value, the variable will be assigned the default value for the type. For non-primitive types, the default value is null
.
Currently, your code is equivalent to:
ThreeColors color = null;
So when you use it, of course you get a NPE. Instead, try something like this:
ThreeColors color = ThreeColors.RED;
Upvotes: 2
Reputation: 37680
The instance of color should be reachable, no?
There is no instance, color
is null
by default, because it is not initialized.
Upvotes: 1
Reputation: 47280
Change to this (or whichever colour you like) :
ThreeColors color = ThreeColors.RED;
Upvotes: 0