Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Code Output

Tags:

java

I've stumbled across some pretty weird code that I'm surprised doesn't cause an error

public class WeirdCode {

    public static int fooField = 42;

    public WeirdCode getFoo(){
        return null; 
    } 
    public static void main(String args[]) {
        WeirdCode foo = new WeirdCode();
        System.out.println(foo.getFoo().fooField); 
    }
}

Surprisingly, it prints out 42! Can anyone explain?

like image 644
Michael Avatar asked Jun 27 '15 01:06

Michael


1 Answers

References to static members of a class are resolved at compile-time. The compiler doesn't care what the value of the expression is, just its type, and so a ((WeirdCode) null).fooField just resolves to WeirdCode.fooField like anything else.

like image 137
chrylis -cautiouslyoptimistic- Avatar answered Nov 06 '22 15:11

chrylis -cautiouslyoptimistic-