gpt4 book ai didi

java - 请帮我理解java结构

转载 作者:行者123 更新时间:2023-12-02 07:21:35 24 4
gpt4 key购买 nike

public class MyDate {
private int day = 1;
private int month = 1;
private int year = 2000;

public MyDate(int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}

public MyDate(MyDate date)
{
this.day = date.day;
this.month = date.month;
this.year = date.year;
}

/*
here why do we need to use Class name before the method name?
*/
public MyDate addDays(int moreDays)
{
// "this" is referring to which object and why?
MyDate newDate = new MyDate(this);
newDate.day = newDate.day + moreDays;

// Not Yet Implemented: wrap around code...
return newDate;
}

public String toString()
{
return "" + day + "-" + month + "-" + year;
}
}

最佳答案

回答1。在方法名称之前使用类名称意味着您将返回 MyDate 类型的引用变量。它只是一个返回类型。

回答2。this 指的是当前对象,即您的 MyDate 类对象。为了使用“new”关键字创建新对象,您可以使用“this”作为快捷方式。但是“this”应该在您尝试引用对象的类中找到。

关于java - 请帮我理解java结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14152206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com