Why do this() and super() have to be the first statement in a constructor?

前端 未结 21 1930
北荒
北荒 2020-11-21 23:10

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

public class MyClass {
    publi         


        
21条回答
  •  情深已故
    2020-11-21 23:31

    So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.

    Actually you can execute logic with several expessions, you just have to wrap your code in a static function and call it in the super statement.

    Using your example:

    public class MySubClassC extends MyClass {
        public MySubClassC(Object item) {
            // Create a list that contains the item, and pass the list to super
            super(createList(item));  // OK
        }
    
        private static List createList(item) {
            List list = new ArrayList();
            list.add(item);
            return list;
        }
    }
    

提交回复
热议问题