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

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

    My guess is they did this to make life easier for people writing tools that process Java code, and to some lesser degree also people who are reading Java code.

    If you allow the super() or this() call to move around, there are more variations to check for. For example if you move the super() or this() call into a conditional if() it might have to be smart enough to insert an implicit super() into the else. It might need to know how to report an error if you call super() twice, or use super() and this() together. It might need to disallow method calls on the receiver until super() or this() is called and figuring out when that is becomes complicated.

    Making everyone do this extra work probably seemed like a greater cost than benefit.

提交回复
热议问题