Can you re-make a method abstract in the inheritance tree?

浪尽此生 提交于 2019-12-02 09:23:50

Yes, You have to redefine the bar(...) as abstract method. Then you have to declare public class FlyingMotorizedVehicle as a abstract class as well

public abstract class FlyingMotorizedVehicle extends MotorizedVehicle {

    @Override
    SomethingElse doOtherStuff(...) {
        return new SomethingElse();
    }

    abstract Foo bar(...);

}

You want children of MotorizedVehicle to have a default implementation of bar, but not so for the children of the FlyingMotorizedVehicle.

abstract class BasicMotorizedVehicle
    // no bar
    ... // Rest of old MotorizedVehicle

class MotorizedVehicle extends BasicMotorizedVehicle
    Foo bar(...) { ... }

class FlyingMotorizedVehicle extends BasicMotorizedVehicle

Brother, study Interfaces too.

If you want some class, such as Vehicle to only provide function prototypes, then you should always use Interface.

And make your FlyingMotorizedVehicle as abstract class.

  • Abstract class can have both types of functions, either prototype only (abstrac functions) or fully implemented functions.
  • Interfaces have only function prototypes, they can't contain function implementations, Interfaces are required to be implemented.

For further study, you can find many useful links, including this one.

=============================CODE-EXAMPLE=======================================

For Vehicle

public interface Vehicle {

    Something doStuff(...);   
    SomethingElse doOtherStuff(...);
    Foo bar(...);

}

For FlyingMotorizedVehicle

public abstract class FlyingMotorizedVehicle extends MotorizedVehicle {

    SomethingElse doOtherStuff(...) {
        return new SomethingElse();
    } 
}

===============================================================================

Happy OOP-ing!

Yes you can. In fact, it even says you can explicitly in the language spec:

An instance method that is not abstract can be overridden by an abstract method.

The problem you are facing is described a few paragraphs up:

The declaration of an abstract method mmust appear directly within an abstract class (call it A) unless it occurs within an enum declaration (§8.9); otherwise a compile-time error occurs.

So, the problem is that your class is not abstract, as others pointed out already; it may just be useful to know the specific parts of the spec which describe it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!