Call the child the parent class constructor

When you create a subclass object, the parent class constructor will be executed first, as a subclass of all first line of the constructor have default implicit super (); statement.

format:

Call the constructor method of the class

this ( argument list );

Null argument constructor call the parent class

super();

There argument constructor call the parent class

super ( argument list );

 

Why create a subclass object constructor must access the parent class? Because subclass inherits the contents of the parent class, so when you create an object, you must look at how the parent class is initialized to their content, see the following procedures:

public class Test {

    public static void main(String[] args) {

        new Zi ();

    }

   

}

class Fu{

    int num;

    Fu () {

        System.out.println ( "Fu constructor " + num);

        a = 4;

    }

}

class Zi extends Fu{

    Day(){

         // super (); call the parent class constructor parameter space

        System.out.println ( "Zi constructor " + num);

    }

}

Results of the:

       Fu constructor 0

       Zi constructor 4

 

By found a subclass constructor execution, call the parent class constructor, which shows sub-class constructor has a super ().

So, constructor of a subclass of why there is an implicit super () do?

The reason: the subclass inherits the contents of the parent class, so subclass initialization, the action must be to perform the initialization of the parent class First parent class. In this way, you can use the contents of the parent class.

When the parent is not null argument constructor configured subclass must have super statement shown, the parent has access to the specified parameters constructor.

Published 118 original articles · won praise 5 · Views 2560

Guess you like

Origin blog.csdn.net/weixin_41874888/article/details/104089391