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

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

    I've found a way around this by chaining constructors and static methods. What I wanted to do looked something like this:

    public class Foo extends Baz {
      private final Bar myBar;
    
      public Foo(String arg1, String arg2) {
        // ...
        // ... Some other stuff needed to construct a 'Bar'...
        // ...
        final Bar b = new Bar(arg1, arg2);
        super(b.baz()):
        myBar = b;
      }
    }
    

    So basically construct an object based on constructor parameters, store the object in a member, and also pass the result of a method on that object into super's constructor. Making the member final was also reasonably important as the nature of the class is that it's immutable. Note that as it happens, constructing Bar actually takes a few intermediate objects, so it's not reducible to a one-liner in my actual use case.

    I ended up making it work something like this:

    public class Foo extends Baz {
      private final Bar myBar;
    
      private static Bar makeBar(String arg1,  String arg2) {
        // My more complicated setup routine to actually make 'Bar' goes here...
        return new Bar(arg1, arg2);
      }
    
      public Foo(String arg1, String arg2) {
        this(makeBar(arg1, arg2));
      }
    
      private Foo(Bar bar) {
        super(bar.baz());
        myBar = bar;
      }
    }
    

    Legal code, and it accomplishes the task of executing multiple statements before calling the super constructor.

提交回复
热议问题