injoy
injoy

Reputation: 4373

'this' pointer not initialized in Java program

I have a program below:

package com.company;

enum Color {
    RED, GREEN;

    Color() {
        System.out.println(Main.getRegionName(this));
    }
}

public class Main {
    public static String getRegionName(Color region) {
        switch (region) {
            case RED:
                return "red";
            case GREEN:
                return "green";
            default:
                return "false";
        }
    }

    public static void main(String[] args) {
        Main m = new Main();
        Color color = Color.RED;
    }
}

When I run the program, I got the exceptions below:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.company.Main.getRegionName(Main.java:13)
    at com.company.Color.<init>(Main.java:7)
    at com.company.Color.<clinit>(Main.java:4)
    at com.company.Main.main(Main.java:25)
Caused by: java.lang.NullPointerException
    at com.company.Color.values(Main.java:3)
    at com.company.Main$1.<clinit>(Main.java:13)
    ... 4 more

What's the reason for it? Is the 'this' initialized for the Color class when it calls Main.getRegionName(this) in its constructor?

Upvotes: 4

Views: 129

Answers (2)

Roberto
Roberto

Reputation: 2185

You shouldn't access the object you are constructing from inside the constructor System.out.println(Main.getRegionName(this));

The 'this' pointer is not initialized while you are inside the constructor.

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

The execution of the code can be described like this:

  • Class Loader loads the enum Color.
  • It calls the constructor of Color for the first value, RED.
  • In the constructor, there's a call to method Main#getRegionName.
  • In method Main#getRegionName, the switch will call to the Color#values to obtain the values of the enum for the switch.
  • Since Color values have not been loaded yet, it breaks by a NullPointerException, and the exception gets propagated.

This behavior is noticed by this line in the stacktrace:

Caused by: java.lang.NullPointerException
at com.company.Color.values(Main.java:3)

More info:

Upvotes: 8

Related Questions