2

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?

1
  • 1
    just make today static in Date Commented Mar 14, 2016 at 18:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments