简体   繁体   中英

Using an overloaded default constructor that calls a three parameter constructor in Java?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM