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

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

    The question of why Java does this has already been answered, but since I stumbled upon this question hoping to find a better alternative to the one-liner, I'll hereby share my work-around:

    public class SomethingComplicated extends SomethingComplicatedParent {
    
        private interface Lambda {
            public T run();
        }
    
        public SomethingComplicated(Settings settings) {
            super(((Lambda) () -> {
    
                // My modification code,
                settings.setting1 = settings.setting2;
                return settings;
            }).run());
        }
    }
    

    Calling a static function should perform better, but I would use this if I insist on having the code "inside" the constructor, or if I have to alter multiple parameters and find defining many static methods bad for readability.

提交回复
热议问题