'How to prevent error recursive constructor invocation [duplicate]
I can't find the solution. I'm using Java 11 and IntelliJ IDEA. Error is in line 10, only removing it gets rid of error, but I need this constructor.
The first time I encounter this error
public class Time2 {
private int seconds;
public Time2()
{
this(0);
}
public Time2(int hour)
{
this(hour*3600);
}
public Time2(int hour, int minute )
{
this(hour * 3600 + minute*60);
}
public Time2(int hour, int minute, int second)
{
if (hour < 0 || hour >= 24)
throw new IllegalArgumentException("hour must be 0-23");
if (minute < 0 || minute >= 60)
throw new IllegalArgumentException("minute must be 0-59");
if (second < 0 || second >= 60)
throw new IllegalArgumentException("second must be 0-59");
this.seconds = hour*3600 + minute*60 + second;
}
public Time2(Time2 time)
{
this(time.getHour(), time.getMinute(), time.getSecond());
}
}
Solution 1:[1]
You have a recursive call between constructors:
public Time2() // A
{
this(0);
}
public Time2(int hour) // B
{
this(hour*3600);
}
public Time2(int hour, int minute ) // C
{
this(hour * 3600 + minute*60);
}
public Time2(int hour, int minute, int second) // D
{
if (hour < 0 || hour >= 24)
throw new IllegalArgumentException("hour must be 0-23");
if (minute < 0 || minute >= 60)
throw new IllegalArgumentException("minute must be 0-59");
if (second < 0 || second >= 60)
throw new IllegalArgumentException("second must be 0-59");
this.seconds = hour*3600 + minute*60 + second;
}
public Time2(Time2 time) // E
{
this(time.getHour(), time.getMinute(), time.getSecond());
}
- A -> B
- B -> B
- C -> B
- D -> -
- E -> D
So for constructors A, B, C, they all call B, and from there on an endless recursive call occurs.
You must correct the C and B constructors:
public Time2(int hour, int minute ) // C
{
this(hour, minute, 0);
}
public Time2(int hour) // B
{
this(hour,0);
}
This way the endless recursiveness is avoided.
- A -> B
- B -> C
- C -> D
- D -> -
- E -> D
Also only in the last (D) constructor the conversion to seconds occur.
PS: You should use Java already existing API to convert to seconds (ex: Duration.ofHours(1).getSeconds()).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
