2016-06-10 65 views
-1

我目前正在用java自学,看着新波士顿的vids。我编写了一个构造函数就像他的代码,但我得到一个错误。无法正确使用构造函数 - 构造函数发生错误

The code from the tutorial compared to my code

这里是我完整的代码在another.java

注:上面的截图及代码下没有类同名,我只是改变它,因为它让我感到困惑。希望你能理解

 public class class2{ 
      private int hour; 
      private int minutes; 
      private int second; 

     public class2(){ 
      this(0,0,0); /** It says "recursive constructor incovation class2(int,int,int)" */ 

     } 

     public class2(int h){ 
      this(h,0,0); /** It says "recursive constructor incovation class2(int,int,int)" */ 
     } 

     public class2(int h, int m){ 
      this(h,m,0); /** It says "recursive constructor incovation class2(int,int,int)" */ 
     } 

     public class2(int h, int m, int s){ 
      this(h,m,s); /** It says "recursive constructor incovation class2(int,int,int)" */ 
     } 
     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){ 
      minutes = ((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 minutes; 
     } 
     public int getSecond(){ 
      return second; 
     } 
     public String printTime(){ 
      return String.format("%02d:%02d:%02d:", getHour(),getMinute(),getSecond()); 
     } 
    } 

它说的错误是 “递归构造incovation的Class2(INT,INT,INT)” 如果你有一个答案,请解释一下也。谢谢!

+1

这就是当您调用自身的构造函数时发生的情况。至少编译器足够聪明,可以警告你,而不是让程序在运行时因堆栈溢出而崩溃。 – azurefrog

回答

4

因为这是递归的:

public class2(int h, int m, int s){ 
    this(h,m,s); /** It says "recursive constructor incovation class2(int,int,int)" */ 
} 

调用此构造函数调用...这个构造。无限地。

如果这是“主”构造函数(所有其他人都调用的构造函数),那么这就是您想要执行实际构造函数逻辑的地方。例如:

public class2(int h, int m, int s){ 
    setTime(h, m, s); 
} 
+1

作为一个侧面说明,从构造函数调用覆盖方法(如'setTime')[通常不是一个好主意](http://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-调用构造函数),最好只用'this.h = h'等初始化变量等。 – Tunaki

+0

@Tunaki:是的。由于在这种结构中有一些深层次的逻辑方法,所以我认为理想情况下逻辑应该被重构为由可覆盖的元素调用的私有setter。 – David

+0

@ David,那么这个新波士顿的东西是在教授错误的编码方式? –