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

后端 未结 5 976
夕颜
夕颜 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条回答
  •  孤街浪徒
    2021-01-12 19:02

    Here is what gets called:

    new Son()
    =>  
      Son._init
       =>  first every constructor calls super()
          Father._init
             Object._init
             who()  => is overridden, so prints "son"
             tell(name) => name is private, so cannot be overridden => "father"
       who()  => "son"
       tell(name)  => "son"   
    

    Lessons to learn:

    • private fields and methods are private. Cannot be overridden.
    • Do not call methods from constructors that can be overridden. This can call methods on half-initialized class state (not happening in your case, though).

提交回复
热议问题