Home  >  Article  >  Java  >  How to call constructor method in java

How to call constructor method in java

(*-*)浩
(*-*)浩Original
2019-05-21 18:08:5312104browse

Java calls the constructor, that is, the subclass calls the constructor of the base class (parent class). How to call, please see the details.

How to call constructor method in java

Rules for constructor methods in subclasses

It must be called during the construction process of a subclass Base class constructor.

Subclasses can use super(argument_list) in their own construction methods to call the construction method of the base class.

If you use this(argument_list) to call another constructor of this class.

If you call super, it must be written in the first line of the subclass constructor.

If the constructor of the subclass does not explicitly call the constructor of the base class, the system calls the parameterless constructor of the base class by default.

If the subclass constructor does not explicitly call the base class constructor, and the base class does not have a parameterless constructor, a compilation error will occur.

The example is as follows:

class SuperClass{
    private int n;
    //SuperClass(){
    //    System.out.println("SuperClass()");
    //}
    SuperClass(int n){
        System.out.println("SuperClass(int n)");
        this.n = n;
    }
}
class SubClass extends SuperClass{
    private int n;
    
    SubClass(){
        super(300);//调用父类的有参构造方法
        System.out.println("SuperClass");
        
    }    
    SubClass(int n){
        System.out.println("SubClass(int n):"+n);
        this.n = n;
    }
}
public class TestSuperSub{
    public static void main (String args[]){
        //SubClass sc = new SubClass();
        SubClass sc2 = new SubClass(200); 
    }
}

Verify the above syntax in turn.

Related learning recommendations: java basic tutorial

The above is the detailed content of How to call constructor method in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn