Multiple Constructors Help
So I'm practicing Java, and I got this code from a Youtube video. The video teaches how to use multiple constructors with different arguments. When I run the program, I get this error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Recursive constructor invocation Tuna(int, int, int)
Recursive constructor invocation Tuna(int, int, int)
Recursive constructor invocation Tuna(int, int, int)
Recursive constructor invocation Tuna(int, int, int)
at time.Tuna.<init>(Tuna.java:8)
at time.Apples.main(Apples.java:7)
My code is almost identical to the video's code, I don't know why it's not working. Any help? Thanks.
Edit: I'm getting errors on the lines that use "this" in the Tuna class. This is kind of an old video, has Java changed since then?
Apple class:
Code:
package time;
public class Apples {
public static void main(String[] args) {
Tuna tunaObject1 = new Tuna();
Tuna tunaObject2 = new Tuna(5);
Tuna tunaObject3 = new Tuna(5,13);
Tuna tunaObject4 = new Tuna(5,13,43);
System.out.printf("%s\n", tunaObject1.toMil());
System.out.printf("%s\n", tunaObject2.toMil());
System.out.printf("%s\n", tunaObject3.toMil());
System.out.printf("%s\n", tunaObject4.toMil());
}
}
Tuna class:
Code:
package time;
public class Tuna {
private int hour, minute, second;
public Tuna(){
this(0,0,0);
}
public Tuna(int h){
this(h,0,0);
}
public Tuna(int h,int m){
this(h,m,0);
}
public Tuna(int h,int m,int s){
this(h,m,s);
setTime(h,m,s);
}
public void setTime(int h,int m,int s){
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h){
hour = ((h>=0&&h<24)?h:0);
}
public void setMinute(int m){
minute = ((m>=0&&m<60)?m:0);
}
public void setSecond(int s){
second = ((s>=0&&s<60)?s:0);
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public int getSecond(){
return second;
}
public String toMil(){
return String.format("%02d:%02d:%02d",getHour(),getMinute(),getSecond());
}
}
Re: Multiple Constructors Help
The constructor with three parameters was calling itself. I commented it out.
public Tuna(int h,int m,int s){
// this(h,m,s); <<<<< this constructor can't call itself.
setTime(h,m,s);
}
Re: Multiple Constructors Help