随笔 - 54  文章 - 0  评论 - 0  阅读 - 3849

this关键字除了在实例方法中,也可以使用在构造方法中

复制代码
//this除了可以使用在实例方法中,还可以使用在构造方法中
/*需求:
    1.定义一个日期类,可以表示年月日信息
    2.需求中要求:
        如果调用无参数构造方法,默认创建的日期为:1997年11月12日
*/
public class test03 {
    public static void main(String[] args) {
        //创建一个对象,调用无参方法中的默认日期
        Date date1 = new Date();
        date1.detail();
        //创建对象date2,调用有参构造
        Date date2 = new Date(2000,11,11);
        date2.detail();
    }
}

//定义日期类
class Date{
    //属性私有化  (用setter、getter方法)
    private int year;
    private int month;
    private int day;

    //无参构造(设置默认日期)
    public Date(){
        this.year = 1997;
        this.month = 11;
        this.day = 12;
        //这里可以用this.(1997,11,12); 来简化
        //this.()表示调用当前类中的其他方法,且只能用在第一行
    }
    //有参构造
    public Date(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }
    //set、get方法
    public void setYear(int year) {
        this.year = year;
    }

    public int getYear() {
        return 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;
    }

    //定义用于打印的方法detail
    public void detail(){
        System.out.println(year+"年"+month+"月"+day+"日");
    }
}
复制代码

 

posted on   三岁学JAVA  阅读(127)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示