【问题标题】:"Constructor cannot be applied to given types" when constructors have inheritance当构造函数具有继承时,“构造函数不能应用于给定类型”
【发布时间】:2017-08-21 23:04:24
【问题描述】:

这是我的基类:

abstract public class CPU extends GameObject {
    protected float shiftX;
    protected float shiftY;

    public CPU(float x, float y) {
        super(x, y);
    }

这是它的子类之一:

public class Beam extends CPU {
    public Beam(float x, float y, float shiftX, float shiftY, int beamMode) {
        try {
            image = ImageIO.read(new File("/home/tab/Pictures/Beam"+beamMode+".gif"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.x = x;
        this.y = y;
        this.shiftX = shiftX;
        this.shiftY = shiftY;
    }

新的构造函数被突出显示,它说:

Constructor CPU in class CPU cannot be applied to given types:
required: float, float
found: no arguments

如何解决?

【问题讨论】:

    标签: java constructor


    【解决方案1】:

    正如错误试图告诉您的那样,您需要将参数传递给基类的构造函数。

    添加super(x, y);

    【讨论】:

      【解决方案2】:

      最终对象需要使用其构造函数之一初始化超类。如果存在默认(无参数)构造函数,则编译器会隐式调用它,否则子类构造函数需要使用super 作为其构造函数的第一行来调用它。

      在你的情况下,那将是:

      public Beam(float x, float y, float shiftX, float shiftY, int beamMode) { 
        super(x, y)
      

      稍后删除对this.xthis.y 的分配。

      另外,请避免将它们设为protected,这会使调试变得困难。而是添加getters,如果绝对必要,添加setters

      【讨论】:

      • 来自docs.oracle.com/javase/tutorial/java/javaOO/constructors.html:您不必为您的类提供任何构造函数,但这样做时必须小心。编译器会自动为任何没有构造函数的类提供无参数的默认构造函数。此默认构造函数将调用超类的无参数构造函数。在这种情况下,如果超类没有无参数构造函数,编译器会报错,因此您必须验证它是否存在。
      • 来自docs.oracle.com/javase/tutorial/java/IandI/super.html:注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类无参数构造函数的调用。
      【解决方案3】:

      我怀疑你应该写

      protected float shiftX;
      protected float shiftY;
      
      public CPU(float x, float y, float shiftX, float shiftY) {
          super(x, y);
          this.shiftX = shiftX;
          this.shiftY = shiftY
      }
      

      public Beam(float x, float y, float shiftX, float shiftY, int beamMode) {
          super(x,y,shiftX,shiftY);
          try {
              image = ImageIO.read(new File("/home/tab/Pictures/Beam"+beamMode+".gif"));
          } catch (Exception e) {
              throw new AssertionError(e);
          }
      }
      

      【讨论】:

        【解决方案4】:

        如果你没有指定任何默认构造函数,那么在编译时它会给你这个错误“类中的构造函数不能应用于给定类型;” 注意:如果您创建了任何参数化构造函数。

        【讨论】:

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