英文:
Using an overloaded default constructor that calls a three parameter constructor in Java?
问题
我正在学习如何使用重载的构造函数。我需要编写一个健身程序,用于跟踪当前的活动、以分钟为单位的时间和日期。在这个程序中,我有一个默认构造函数和一个三参数构造函数。当在默认构造函数中调用三参数构造函数时,我收到一个错误,指出“FitnessTracker2(String, int, LocalDate)的方法对于FitnessTracker2类型是未定义的”,而调用中的LocalDate参数似乎是导致此错误的原因。我尝试过重新排列构造函数并更改它们的名称,但迄今为止我尝试过的所有方法都没有任何作用。
import java.time.*;
public class FitnessTracker2 {
String activity;
int minutes;
LocalDate date;
public FitnessTracker2() {
this("running", 0, LocalDate.of(2020, 1, 1));
}
public FitnessTracker2(String a, int m, LocalDate d) {
activity = a;
minutes = m;
date = d;
}
public String getActivity() {
return activity;
}
public int getMinutes() {
return minutes;
}
public LocalDate getDate() {
return date;
}
}
英文:
I'm learning about using overloaded constructors. One of the programs I need to write is a fitness program that keeps track of the current activity, time in minutes, and the date. In this program, I have both a default constructor and a three parameter constructor. When calling the three parameter constructor in the default constructor, I get an error saying "The method FitnessTracker2(String, int, LocalDate) is undefined for the type FitnessTracker2" and the LocalDate parameter of the call is what seems to be causing it. I've tried reordering the constructors and changing the names of them and everything I've tried so far gets me nowhere.
import java.time.*;
public class FitnessTracker2 {
String activity;
int minutes;
LocalDate date;
public FitnessTracker2() {
FitnessTracker2("running", 0, LocalDate.of(1,1,2020));
}
public FitnessTracker2(String a, int m, LocalDate d) {
activity = a;
minutes = m;
date = d;
}
public String getActivity() {
return activity;
}
public int getMinutes() {
return minutes;
}
public LocalDate getDate() {
return date;
}
}
答案1
得分: 3
当从默认构造函数调用另一个构造函数时,您需要使用this
关键字来引用它,而不是使用类名。
public FitnessTracker2() {
this("running", 0, LocalDate.of(1, 1, 2020));
}
英文:
When calling the other constructor from your default constructor, you need to refer to it using the this
keyword, not the class name.
public FitnessTracker2() {
this("running", 0, LocalDate.of(1, 1, 2020));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论