Stumbler
Stumbler

Reputation: 2146

Enum NullPointerException

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

Answers (7)

Ajinkya
Ajinkya

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

MichaelS
MichaelS

Reputation: 6032

You have to initialize color. Try color = ThreeColors.RED; or color = ThreeColors.BLUE; or color = ThreeColors.green;!

Upvotes: 1

Kevin Workman
Kevin Workman

Reputation: 42176

Your color variable is null. You have to initialize it to use it.

Upvotes: 4

Bohemian
Bohemian

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

mareckmareck
mareckmareck

Reputation: 1580

You do not initialize color variable.

Upvotes: 0

Joffrey
Joffrey

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

NimChimpsky
NimChimpsky

Reputation: 47280

Change to this (or whichever colour you like) :

ThreeColors color = ThreeColors.RED;

Upvotes: 0

Related Questions