this()基础用法

this()表示调用构造方法,此种调用只能用在构造方法中,即构造方法中调用构造方法this(实参)。

1、this()、this(实参)必须方法构造方法的第一行

2、在有参数构造方法中调用无参数构造方法this();在无参数的构造方法中调用有参数的构造方法this(实参)

一、如下是无参数构造方法调用有参数构造方法:

public class Constractor
{
    int year;
    int month;
    int day;
    
    //无参数构造方法
    public Constractor()
    {
        this(2019,1,1);
    
    }

    //有参数构造方法
    Constractor(int year, int month, int day)
    {
        
        this.year = year;
        this.month = month;
        this.day = day;
    }

}

二、如下是有参数构造方法调用无参数构造方法:

public class Constractor
{
    int year;
    int month;
    int day;
    
    //无参数构造方法
    public Constractor()
    {
    
    }

    //有参数构造方法
    Constractor(int year, int month, int day)
    {
        this();
        
        this.year = year;
        this.month = month;
        this.day = day;
    }

}

 三、this()/this(实参)必须出现在构造方法的第一行,否则报错

猜你喜欢

转载自www.cnblogs.com/jesse-zhao/p/10660439.html
今日推荐