I was trying to make a class "Date" in Java so I wrote this:
class Date { private int year, month, day; Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } Date today = new Date(2016,3,14); public int addDaysTo(Date someDate) { // <<------- this supposed to calculate number of days required to achieve passed date from today int def = convToDays(someDate) - convToDays(today); if (def < 0) return -1; return def; } } This gives me an error: stack overflow. I think this was because of the line
Date today = new Date(2016,3,14); I understand initializing an object inside its own class would cause an infinite loop, but if I need to identify some Date constant to be used like in addDaysTo method, what should I do?!
I tried moving the problematic line to a new class and make it static like this:
class stupidSol { static Date today = new Date(2016,3,14); } This worked (after replacing today by stupidSol.today of course) but I think there might be an easier way. Is there?