Title: could i initialize an object inside it's class?
Tags: java
Question: 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?
Comment: just make today static in Date

Here is the accepted answer: Yes, this line leads to a stack overflow error.
Date today = new Date(2016,3,14);
You have found what causes it, and here is why.  When you create a Date, it has as an instance variable today, which creates another Date, which creates another Date, and so on, until your stack overflows.
Making it static solves the problem, because then today is initialized only once, and not as part of every instance that is created.
You made it as part of another class, which will work, but you can make it static within your own Date class, to make it cleaner, more understandable, and more readable.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:03/14/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java>', 'Title': "could i initialize an object inside it's class?", 'ViewCount': 90, 'id': 35995724, 'user_AboutMe': None, 'user_AccountId': None, 'user_DisplayName': None, 'user_Reputation': None, 'user_Views': None, 'user_id': None}}