What is the order of the Constructors in this Java Code?

后端 未结 5 1006
夕颜
夕颜 2021-01-12 18:36

Here is the code, I defined two class named Father and Son, and create them in the main function:

public class Test {
    public static void main(String[] ar         


        
5条回答
  •  萌比男神i
    2021-01-12 19:22

    The code above is particular Bad Style (TM). ;-)

    What happens is: There is no Father instance, just a Son instance. (It is assignment compatible to Father, however.)

    The Son constructor calls the Father constructor. The latter calls the overridden (!) methods, thus Father.who and Father.tell are never called! The overridden Methods are called before (!) the Son constructor was finished.

    My recommendations:

    1. If you call a method in a constructor, make it final. Or make the whole class final. Or make the called method private at least.
    2. Never override a method called in a constructor.
    3. If you have to violate above recommendations, write extensive comments about why you did so and what you expect to happen. Write a unit test to make sure your assumptions are valid.

提交回复
热议问题