【问题标题】:Undefined type compile error when trying to define multiple constructors尝试定义多个构造函数时出现未定义类型编译错误
【发布时间】:2016-02-04 12:18:21
【问题描述】:

主类->>>

public class scoreMain {

    public static void main(String[] args) {
        // Football Score board

        Score scoreObject = new Score();
        Score scoreObject1 = new Score(1);
        Score scoreObject2 = new Score(1,2);
        Score scoreObject3 = new Score(1,2,3);

    }
}

和构造函数类-->>>

public class Score {

    public void Score()
    {
        Score(0,0,0);
    }
    public void Score(int x)
    {
        Score(x,0,0);
    }
    public void Score(int x,int y)
    {
        Score(x,y,0);
    }
    public String Score(int x,int y,int z)
    {
       Score(x,y,z);
       return String.format("%d/%d%d",x,y,z);   
    }
}

但在创建对象时显示错误... 构造函数 score(int) 未定义 构造函数 score(int int) 未定义 构造函数得分(int int int)未定义

【问题讨论】:

    标签: java


    【解决方案1】:

    构造函数不返回任何内容。不是String 也不是void 或其他任何东西。您应该按如下方式更改构造函数:

    public class Score {
    
        public Score() {
            this(0,0,0);
        }
    
        public Score(int x) {
            this(x,0,0);
        }
    
        public Score(int x,int y){
            this(x,y,0);
        }
    
        public Score(int x,int y,int z) {
           Score(x,y,z); // Not sure what's this - you can't do a recursive constructor call. Doesn't make any sense
           return String.format("%d/%d%d",x,y,z); // Remove the return statment.
        }
    }
    

    还要注意,不仅不要对任何值进行返回,而且在最后一个重载的构造函数中对构造函数进行了递归调用。这没有任何意义,也不会起作用。

    顺便说一句 - 重载构造函数的正确方法是在重载中调用 this() 并且只有一个实现。更多详情请查看this question

    【讨论】:

      【解决方案2】:

      在您的代码中,只有方法,没有构造函数。构造函数没有返回类型。

      例子:

      public class Score {
      
        public Score()
        {
          this(0,0,0);
        }
      
        public Score(int x)
        {
          this(x,0,0);
        }
      
        public Score(int x,int y)
        {
          this(x,y,0);
        }
      
        public Score(int x,int y,int z)
        {
          //??
          //constructors cannot return anything!
          //return String.format("%d/%d%d",x,y,z);   
        }
      }
      

      【讨论】:

        【解决方案3】:

        另外,要调用同一个类的其他构造函数,你应该使用关键字this,而不是类名。

        所以,第一个构造函数应该是这样的

        public void Score()
        {
            this(0,0,0);
        }
        

        另外,你在这里拥有的是一个方法,而不是一个构造函数。构造函数没有返回类型

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多