Unexpected behavior. Is this where java does compile time optimizations?

Please have a look at this piece of code:

class Ideone
{
    static int value = 3;

    Ideone getIdeone()
    {
        System.out.println("getIdeone() called");
        return null;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Ideone ideone = new Ideone();
        System.out.println(ideone.getIdeone().value);
    }
}

      

Output:

getIdeone () is called

3

Perfect link here

As you must have observed, I am calling a call getIdeone()

that returns null

and then retrieves value

from a null object.

What's going on here? Does the compiler do some compile time optimizations and picks value

directly from the class because it is static?

+3


source to share


1 answer


Since value

is a field static

, you don't need an instance to access it, so it null

will suffice. It really comes directly from the class.

The compiler already warns about this:

The static field Ideone.value must be accessible in a static way




For a bonus exercise, see what happens when subclasses are involved. The code below will give this output:

getIdeone () in a test called

3

(so not 5

), although (at runtime) it is expected to getIdeone()

return Test

. This is because the compiler has already turned this into a static field call Ideone

- it doesn't matter what happens at runtime.

public class Ideone {
    static final int value = 3;

    Ideone getIdeone() {
        System.out.println("getIdeone() called");
        return null;
    }

    public static void main(String[] args) throws java.lang.Exception {
        Ideone ideone = new Ideone().new Test();
        System.out.println(ideone.getIdeone().value);
    }

    class Test extends Ideone {
        static final int value = 5;

        @Override
        Test getIdeone() {
            System.out.println("getIdeone() in Test called");
            return null;
        }
    }
}

      

+10


source







All Articles