爲何this()和super()必須是構造函數中的第一條語句?

問題:

Java requires that if you call this() or super() in a constructor, it must be the first statement. Java要求,若是您在構造函數中調用this()或super(),則它必須是第一條語句。 Why? 爲何? express

For example: 例如: app

public class MyClass {
    public MyClass(int x) {}
}

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        int c = a + b;
        super(c);  // COMPILE ERROR
    }
}

The Sun compiler says "call to super must be first statement in constructor". Sun編譯器說「對super的調用必須是構造函數中的第一條語句」。 The Eclipse compiler says "Constructor call must be the first statement in a constructor". Eclipse編譯器說「構造函數調用必須是構造函數中的第一條語句」。 函數

However, you can get around this by re-arranging the code a little bit: 可是,您能夠經過從新安排一些代碼來解決此問題: ui

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        super(a + b);  // OK
    }
}

Here is another example: 這是另外一個示例: this

public class MyClass {
    public MyClass(List list) {}
}

public class MySubClassA extends MyClass {
    public MySubClassA(Object item) {
        // Create a list that contains the item, and pass the list to super
        List list = new ArrayList();
        list.add(item);
        super(list);  // COMPILE ERROR
    }
}

public class MySubClassB extends MyClass {
    public MySubClassB(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(Arrays.asList(new Object[] { item }));  // OK
    }
}

So, it is not stopping you from executing logic before the call to super. 所以,這不會阻止您在調用super以前執行邏輯 It is just stopping you from executing logic that you can't fit into a single expression. 這只是在阻止您執行沒法包含在單個表達式中的邏輯。 spa

There are similar rules for calling this() . 調用this()有相似的規則。 The compiler says "call to this must be first statement in constructor". 編譯器說「對此的調用必須是構造函數中的第一條語句」。 .net

Why does the compiler have these restrictions? 爲何編譯器有這些限制? Can you give a code example where, if the compiler did not have this restriction, something bad would happen? 您可否舉一個代碼示例,若是編譯器沒有此限制,那麼會發生很差的事情嗎? rest


解決方案:

參考一: https://stackoom.com/question/4twH/爲何this-和super-必須是構造函數中的第一條語句
參考二: https://oldbug.net/q/4twH/Why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor
相關文章
相關標籤/搜索