构造函数不能应用于给定的类型;

时间:2018-04-04 06:38:05

标签: java

我有一个名为Shape的基类,其中Point是另一个只包含x和y坐标的类:

abstract class Shape implements Comparable<Shape> {
  public Point position;
  public double area;


  public Shape(Point p){
    position.x  = p.x; 
    position.y  = p.y;
  }

现在我有一个名为Rectangle的类,它扩展了Shape 注意:position的类型为Point。

public Rectangle(Point p0, double w, double h) {
    // Initializing the postition 
    super(Point(0,0));
    position.x = p0.x;
    position.y = p0.y; 
    // Initializing the height and the width 
    width = w;
    height = h;
} 

现在我知道需要首先使用super来调用Shape构造函数,但现在编译器告诉它无法找到符号。你是如何解决这个问题的? 这是错误:

    ./Rectangle.java:21: error: constructor Shape in class Shape cannot be applied to given types;
  {  // Initialzing of the postition 
  ^
  required: Point
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

3 个答案:

答案 0 :(得分:2)

您的代码将是:

public Rectangle(Point p0, double w, double h)
{
    // Initialzing of the postition 
    super(p0);
    // Initialzing the height and the width 
    width = w;
    height = h;
} 

因为你的超级是Shape构造函数。

您确定Rectangle延长了Shape吗?如果您可以发布您的课程Rectangle定义

答案 1 :(得分:0)

你可以这样做..

public Rectangle(Point p0, double w, double h) {
    // Initializing the postition 
    super(new Point(0,0));
    position.x = p0.x;
    position.y = p0.y; 
    // Initializing the height and the width 
    width = w;
    height = h;
} 

您在超级构造函数中错过了新关键字。

答案 2 :(得分:0)

我猜您的课程类似于:

public class Point {

    public int x;
    public int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Shape {
    public Point position;

    public Shape(Point p) {
        position.x = p.x;
        position.y = p.y;
    }
}

Rectangle类的超级构造函数应该接收一个Point对象,因为它从Shape扩展,构造函数参数是一个Point,因此该类应如下所示:

public class Rectangle extends Shape{

    public double width;
    public double height;

    public Rectangle(Point p0, double w, double h) { 
        // Initialzing of the postition
        super(p0);

        // Initialzing the height and the width
        width = w;
        height = h;
    }
}