简体   繁体   English

尽管实现了具体的类方法,但抽象类仍然不断抛出异常

[英]concrete class method keeps throwing an exception from abstract class despite implementation

I have an abstract class Automobile which has an unimplemented method called move so 我有一个抽象类Automobile,它有一个未实现的方法,称为move so

public abstract class Automobile {
   public void move() {
       throw new UnsupportedOperationException();
   }
}

I have a concrete class which extends my abstract class and implements the move method.My problem is the method keeps throwing an UnsupportedOperationException 我有一个具体的类扩展了我的抽象类并实现了move方法。我的问题是该方法不断抛出UnsupportedOperationException

public class Car extends Automobile{
  int x; 
   public void move(){
    x++;
   }
}

It could be for many reasons in your concrete class: maybe your concrete doesn't actually extends Foo ? 在您的具体课程中可能有很多原因:也许您的具体内容实际上并未扩展Foo Or maybe it calls super.move() somewhere in its body. 或者,它可能在其体内某处调用super.move()

Instead of throwing an exception, the correct way is to define the class and method as abstract to force subclasses to override it. 正确的方法不是抛出异常,而是将类和方法定义为abstract以迫使子类覆盖它。

public abstract class Foo {
    public abstract void move();
}

Please note if Foo only has abstract methods, like in the example above, that's an interface that you want, not an abstract class. 请注意,如果Foo仅具有抽象方法(如上例中所示),则这是您想要的interface ,而不是抽象类。 Also, you should name it to define a behaviour 另外,您应该命名它以定义行为

public interface Moving { 
    void move();
}

And then: 接着:

public class MovingObject implements Moving {
    ....
    @Override
    public void move() {
       // your implementation
    }
    ....
}

Are you calling super.move() in your implementation class? 您要在实现类中调用super.move()吗? Eclipse generates that call by default if you used Source->Override/Implement Methods... 如果您使用Source-> Override / Implement Methods ...,则Eclipse默认生成该调用。

Otherwise I think, that you did not override the method correctly. 否则,我认为您没有正确覆盖该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM