Why can't I refer to an instance method while explicitly invoking a constructor?

后端 未结 6 1630
青春惊慌失措
青春惊慌失措 2020-12-01 08:53

Does anyone know why you can reference a static method in the first line of the constructor using this() or super(), but not a non-sta

6条回答
  •  长情又很酷
    2020-12-01 09:51

    See the Java Language Specification 8.8.7.1. This states that

    An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

    This is because you can not call an instance method before the instance is created. By the way, it is possible to call an instance method later on in the constructor (although not a solution for you).

提交回复
热议问题