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

前端 未结 21 1977
北荒
北荒 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:36

    I totally agree, the restrictions are too strong. Using a static helper method (as Tom Hawtin - tackline suggested) or shoving all "pre-super() computations" into a single expression in the parameter is not always possible, e.g.:

    class Sup {
        public Sup(final int x_) { 
            //cheap constructor 
        }
        public Sup(final Sup sup_) { 
            //expensive copy constructor 
        }
    }
    
    class Sub extends Sup {
        private int x;
        public Sub(final Sub aSub) {
            /* for aSub with aSub.x == 0, 
             * the expensive copy constructor is unnecessary:
             */
    
             /* if (aSub.x == 0) { 
              *    super(0);
              * } else {
              *    super(aSub);
              * } 
              * above gives error since if-construct before super() is not allowed.
              */
    
            /* super((aSub.x == 0) ? 0 : aSub); 
             * above gives error since the ?-operator's type is Object
             */
    
            super(aSub); // much slower :(  
    
            // further initialization of aSub
        }
    }
    

    Using an "object not yet constructed" exception, as Carson Myers suggested, would help, but checking this during each object construction would slow down execution. I would favor a Java compiler that makes a better differentiation (instead of inconsequently forbidding an if-statement but allowing the ?-operator within the parameter), even if this complicates the language spec.

提交回复
热议问题