Thursday, August 6, 2015

[Java][Resolved] Cannot reference a field before it is defined

Error message :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    at static1.main(static1.java:12)

class static1 {
    static {
        ++staticVar;
    }
    static int staticVar ;
    static {
        ++staticVar;
    }
    public static1() {
        System.out.println("Constructor:" + staticVar);
    }
    public static void main(String args[]) {
        new static1();
    }
}
The first static initiation block cannot get the static valuable “staticVar” during the compilation, this causes the compilation error. To solve that, define the static valuable “staticVar” before using that.

class static1 {
    static int staticVar ;
    static {
        ++staticVar;
    }
    static {
        ++staticVar;
    }
    public static1() {
        System.out.println("Constructor:" + staticVar);
    }
    public static void main(String args[]) {
        new static1();
    }
}

1 comment :

  1. 咦, 你唔系學緊 php 咩,無來一排又走左去搞 java?

    ReplyDelete