Method executed prior to Default Constructor

This question already has an answer here:

  • Are fields initialized before constructor code is run in Java? 4 answers

  • Instance variable initialization expressions such as int var = getVal(); are evaluated prior to the constructor execution. Therefore getVal() is called before the constructor is executed.


    Constructor is called prior to method. The execution of method occurs after that which is a part of object creation in which instance variables are evaluated. This could be better understand from following code.

    class SuperClass{
        SuperClass(){
            System.out.println("Super constructor");
        }
    }
    public class ChkCons extends SuperClass{
    
        int var = getVal();
    
        ChkCons() {
            System.out.println("I'm Default Constructor.");
        }
    
        public int getVal() {
            System.out.println("I'm in Method.");
            return 10;
        }
    
        public static void main(String[] args) {
    
            ChkCons c = new ChkCons();
    
        }
    
    }
    

    The above code has following output

    Super constructor
    I'm in Method.
    I'm Default Constructor.
    

    Here the compiler automatically adds super(); as the first statement in ChkCons() constructor, and hence it is called prior to the getVal() method.


    Whenever you create an instance of a class instance variables are initialized first followed by execution of the Constructor

    Ref : Are fields initialized before constructor code is run in Java?

    链接地址: http://www.djcxy.com/p/3484.html

    上一篇: 为什么main方法在java中很重要?

    下一篇: 在默认构造函数之前执行的方法