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 after the super class constructor is executed but prior to the execution of the current class constructor's body.

    Therefore getVal() is called before the body of the ChkCons 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.


    We can refer the following oracle documentation on Initializing instance variables (Emphasis is mine):

    Initializing Instance Members

    Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

    Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

    { // whatever code is needed for initialization goes here }

    > The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

    A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:

    class Whatever {
    private varType myVar = initializeInstanceVariable();
    
    protected final varType initializeInstanceVariable() {
    
        // initialization code goes here
    } 
    }
    

    https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

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

    上一篇: 如何在C ++中声明一个原子向量

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