OscarRyz
OscarRyz

Reputation: 199234

Why class level attributes work with Null

I would think the following would throw NullPointerException

class N { 
    static int i;
    public static void main( String ... args ) { 
        System.out.println( ((N)null).i );
    }
}

But it doesn't. Why?

Upvotes: 3

Views: 88

Answers (1)

Andrey
Andrey

Reputation: 60065

Because i is static (class level) member. It exists for class, for every object of it. So it really doesn't require reference to object, so this part ((N)null) is actually ignored, except for type inference. It could and should be replaced with N.i.

Upvotes: 6

Related Questions