0

我知道其他人遇到了与我非常相似的问题,我尝试将这些答案应用于我的代码,但它仍然无法正常工作,所以我希望你们中的一个人能够查看我的代码并解释我哪里出错了……

这是我的代码:

public class Square extends Rectangle{
String Colour;

    public Square (int x, int y, int h, int w, String Co){
    super (x,y,h,w);
    Colour=Co;
    System.out.println("Constructing a Square now");
    }
        public void showColour(){
        System.out.println("The colour of the square is " + Colour);
        }
}

第二部分:

public class InheritProgram {
public static void main (String [] args){
Square One= new Square (10,20, 15, 15, "blue");

Square colour =new Square();
colour.showColour();

//GeometricShape center= new displayCenter();

}
}

这是我得到的错误:

C:\Users\Karen\Documents\Java\Lab8-1\InheritProgram.java:5: error: constructor Square in class Square cannot be applied to given types;
Square colour =new Square();
               ^
  required: int,int,int,int,String
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Tool completed with exit code 1

任何帮助将不胜感激

4

2 回答 2

5

在这一行:

Square colour =new Square();

...您正在尝试为 - 调用无参数构造函数,Square但您尚未声明一个。您只声明了带有 5 个参数的构造函数,因此您必须使用它来创建一个新实例。

目前尚不清楚您为什么要创建第二个实例-您为什么不直接showColour打电话One

(顺便说一句,我强烈建议您开始遵循 Java 命名约定,并将您的字段也设为私有。如果您的缩进与问题中的内容相匹配,请也修复它 - 这将使您的代码更易于阅读。大多数 IDE 允许您非常轻松地格式化代码。)

于 2013-07-15T18:42:22.357 回答
0

除了上面的答案,您应该已经注意到 stacktrace,它说明了一切。

Square colour =new Square();
required: int,int,int,int,String
found: no arguments

它说它需要(唯一)具有参数 int、int、int、int、String 的构造函数,但是您调用了无参数构造函数。

于 2013-07-15T18:46:41.107 回答