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: 12145
Reputation: 22730
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: 6042
You have to initialize color
. Try color = ThreeColors.RED;
or color = ThreeColors.BLUE;
or color = ThreeColors.green;
!
Upvotes: 1
Reputation: 42174
Your color
variable is null. You have to initialize it to use it.
Upvotes: 4
Reputation: 425448
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: 37879
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: 47310
Change to this (or whichever colour you like) :
ThreeColors color = ThreeColors.RED;
Upvotes: 0