首页 > 其他分享 >this()

this()

时间:2022-11-12 18:33:23浏览次数:34  
标签: int day year month public minute

this()的应用

1.在构造方法里使用
2.语句必须在构造方法体中的第一行

示例代码

package com.powernode.oo;

public class Time {
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private int second;

    public Time() {

    }

    public Time(int year, int month, int day, int hour, int minute, int second) {
        this.year = year;
        this.month = month;
        this.day = day;
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getHour() {
        return hour;
    }

    public void setHour(int hour) {
        this.hour = hour;
    }

    public int getMinute() {
        return minute;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }

    public int getSecond() {
        return second;
    }

    public void setSecond(int second) {
        this.second = second;
    }

    public void printTime(){
        System.out.println(year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒");
    }
}

测试代码

package com.powernode.oo;

public class TimeTest {
    public static void main(String[] args) {
        Time t1 = new Time();
        t1.printTime();

        Time t2 = new Time(2008, 8, 8, 8, 8, 8);
        t2.printTime();
    }
}

运行结果

此时我们看到控制台输出了两条结果,一是无参构造方法的赋值结果,二是全参构造方法的赋值结果

在我们提出一个需求,要求把将默认无参构造方法输出的时间改为1970年1月1日0时0分0秒,在这里我们就用this()

只需要在无参构造方法体中加入以下语句

public Time() {
        this(1970, 1,1,0,0,0);
    }

运行结果

标签:,int,day,year,month,public,minute
From: https://www.cnblogs.com/bcc0729/p/16884382.html

相关文章