简体   繁体   中英

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?

Because color is not initialized and it's default value is null .
Initialize it like

ThreeColors color = ThreeColors.RED;  //Or any other value

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

The instance of color should be reachable, no?

There is no instance, color is null by default, because it is not initialized.

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;

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

您没有初始化color变量。

更改为此(或您喜欢的颜色):

ThreeColors color = ThreeColors.RED;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM