使用在Java中调用三参数构造函数的重载默认构造函数?

huangapple go评论80阅读模式
英文:

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));
}

huangapple
  • 本文由 发表于 2020年9月15日 23:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63905680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定