Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' pointer not initialized in Java program

Tags:

java

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?

like image 364
injoy Avatar asked Jan 08 '23 11:01

injoy


2 Answers

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:

  • How is values() implemented for Java 6 enums?
like image 184
Luiggi Mendoza Avatar answered Jan 14 '23 16:01

Luiggi Mendoza


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.

like image 23
Roberto Avatar answered Jan 14 '23 16:01

Roberto