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

后端 未结 4 588
春和景丽
春和景丽 2021-01-25 03:09

EDIT:

To be clear: The fact that the design is quite ugly is not the point. The point is, that the design is there and I am in the situation to have to add another sub-c

相关标签:
4条回答
  • 2021-01-25 03:28

    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.

    0 讨论(0)
  • 2021-01-25 03:29

    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
    
    0 讨论(0)
  • 2021-01-25 03:35

    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!

    0 讨论(0)
  • 2021-01-25 03:36

    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(...);
    
    }
    
    0 讨论(0)
提交回复
热议问题