Polymorphic method in Constructor (Java)

前端 未结 4 2151
温柔的废话
温柔的废话 2021-02-08 09:46

Class A calls the public method f() in the Constructor. Class B overrides method f() with its own implementation.

Suppose you inta

4条回答
  •  半阙折子戏
    2021-02-08 10:10

    I'll just provide a link, since I'm not very well-informed on the subject. See here for a tutorial that talks about the invocation order of constructors.

    The most prominent quote at the end of the page related to the situation you describe is the following:

    1. The base-class constructor is called. This step is repeated recursively such that the root of the hierarchy is constructed first, followed by the next-derived class, etc., until the most-derived class is reached.
    2. Member initializers are called in the order of declaration. The body of the derived-class constructor is called.

    So, as you've shown in your example, the base-class is initialised, then each of the following classes is instatiated and finally the member variables are initialised.

    But as Bill as mentioned, this is not a good practice. Follow what Bill says. He has more rep than me.

    EDIT: For a more complete answer, see this Jon Skeet answer. The link in this answer is broken, and only a pdf copy of the JLS can be found AFAIK. Here is a copy of the JLS in .pdf format. The relevant section is Section 8.8.7.1. There is an explanation of what the constructor invocation order is in that answer.

提交回复
热议问题