为什么不编译我的代码,错误是说已经在类[closed]中声明了您的方法

问题描述 投票:-3回答:2

在该类中,构造函数有一个“ this”关键字,它将允许它调用其他构造函数,但是每次我这样做时。它出现一个错误,指出不能“在RandomTest类型中复制方法RanodmTest”:为什么?

public class RandomTest 
{

      private String message;
      private boolean answer;

      public String toString()
      {
        return message;
      }

      public RandomTest() {}

      public RandomTest(String s) {
        this.message = s;
      }

      public RandomTest(String mes, boolean res) {
          this.message = mes;
          this.answer = res;
      }

      public RandomTest(String m) {
          this(m);
      }

      public RandomTest(String b, boolean s) 
      {
          this(b, s);
      }

}
java constructor compiler-errors this
2个回答
-1
投票
中复制方法RanodmTest。

您不能使构造函数具有相同的参数,因为您将无法彼此区分。其他构造函数没有任何作用,例如,如果您想要默认的布尔值答案,那么放置“ this”的示例就是这样,只有一个String的构造函数将调用this(string,defaultboolean)。


-1
投票

具有单个参数的构造函数RandomTest(String)和具有2个参数的RandomTest(String b,boolean s)已在类RandomTest中定义。

您可以删除最后两个方法,然后代码可以正常工作。

public class RandomTest {

  private String message;
  private boolean answer;

  public String toString()
  {
    return message;
  }

  public RandomTest() {}

  public RandomTest(String s) {
    this.message = s;
  }

  public RandomTest(String mes, boolean res) {
      this.message = mes;
      this.answer = res;
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.