【问题标题】:abstract class errors simple class抽象类错误 简单类
【发布时间】:2016-07-23 11:15:46
【问题描述】:
public abstract class Shape{
    
    protected Point position;
    
    public Shape (Point p)
    {
        this.position=new Point(p);
    }
    
    public abstract int getArea();
    public abstract int gerPerimeter();
    public abstract boolean overlap(Shape other);
    
}
public class Rectangle extends Shape
{
    public int width;
    public int height;
    
    public Rectangle(Point position,int width,int height)
    {
        super(position);
        this.width=width;
        this.height=height;
    }
    @Override
    public int getArea()
    {
        return width*height;
    }
    @Override
    public int getPerimeter()
    {
        return width*2+height*2;
    }
    @Override
    public boolean overlap(Rectangle other)
    {
        return false;
    }
}
    

Rectangle.java:1: 错误:Rectangle 不是抽象的,并且不会覆盖 Shape 中的抽象方法重叠(Shape)

公共类 Rectangle 扩展 Shape
^

Rectangle.java:17: 错误:方法没有覆盖或实现超类型中的方法

@Override
^

Rectangle.java:22: 错误:方法没有覆盖或实现超类型中的方法

@Override
^

3 个错误

【问题讨论】:

    标签: java class abstract


    【解决方案1】:

    这个方法public boolean overlap(Rectangle other)和这个

    public abstract boolean overlap(Shape other);不一样,

    即使 Rectangle 扩展/实现 Shape...

    所以从技术上讲,您并没有覆盖抽象类的所有方法...

    Override 注释给你一个抱怨,因为该方法可以在超类中找到....

    【讨论】:

      【解决方案2】:

      Rectangleoverlap 方法必须具有与父类方法相同的签名才能覆盖它:

      @Override
      public boolean overlap(Shape other)
      {
          return false;
      }
      

      如果您要求传递给RectangleoverlapShapeRectangle,您可以使用instanceof 检查类型:

      @Override
      public boolean overlap(Shape other)
      {
          if (other instanceof Rectangle) {
              Rectangle otherRect = (Rectangle) other;
              ...   
          }
          return false;
      }
      

      【讨论】:

        【解决方案3】:

        对于错误信息

        Rectangle.java:17:错误:方法没有覆盖或实现 来自超类型的方法

        @Override

        你会注意到你的 Rectangle 类只是 shape 类的子类,这意味着像

        @Override
        public boolean overlap(Rectangle other)
        

        会出错,因为 java 期望超类应该有方法overlap(Rectangle other)。相反,它看到overlap(Shape other),它们完全不同。 解决方法:如果你还想要这个方法,那就去掉@Override注解吧。

        对于错误信息

        Rectangle.java:22:错误:方法没有覆盖或实现 来自超类型的方法

        @Override

        你还没有重写你必须的方法。 解决方案:要么将overlap(Rectangle other) 更改为overlap(Shape other),要么完全编写一个新的覆盖方法,如下所示:

        @Override
        public boolean overlap(Shape other)
        {
            return false;
        }
        

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-16
          • 1970-01-01
          • 2013-09-24
          • 2015-08-05
          • 1970-01-01
          • 1970-01-01
          • 2013-05-13
          相关资源
          最近更新 更多