java: call method_constructor between child class and parent class

Review the basics:

1. If there is no constructor defined in a class, the compiler will automatically add the default no-argument constructor when compiling

Definition format: public ClassName() {}

2. The difference between this and super.

3. Each class is directly or indirectly a subclass of Object, and Object has only one no-argument constructor.

4. The compiler will implicitly add the default parameterless constructor of the parent class in the first line of each constructor, that is, add super().

 

Easy mistakes to make:

class Family extends Object {

public Family(int member) {

}

}

class Father extends Family {

public Father() {

}

}

 

The above code produces a compile error:

Implicit super constructor Family() is undefined. Must explicitly invoke another constructor

 

Because the parent class defines a constructor with parameters, the compiler will not add a default parameterless constructor,

But because a constructor of the parent class is not explicitly called in the constructor of the subclass, the compiler will automatically add the super() method,

However, there is no default no-argument constructor in the parent class, so the default no-argument constructor is undefined error.

 

Modified code:

class Family extends Object {

public Family(int member) {

}

}

class Father extends Family {

public Father() {

super(6);

}

}


In this way, a constructor of the parent class is explicitly called in the constructor of the subclass, so the compiler will not automatically add the super() method.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326630599&siteId=291194637