pepoluan
pepoluan

Reputation: 6808

Abstract Class must override an abstract method?

Let's say this abstract class:

abstract public class MyBase {

    abstract public int GetValue();

    <some concrete methods here>
}

Now I want to inherit that as another abstract class, implementing GetValue() but adding new abstract methods:

abstract public class MyBase2 : MyBase {

    abstract public int GetValue2();

    public override int GetValue() {
        // some code here
        return something;
    }

}

Why do I have to specify override for MyBase2.GetValue()? Isn't MyBase.GetValue() already marked as abstract and thus will naturally be overridden by anything inheriting from MyBase?

Upvotes: 4

Views: 327

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23298

Since your MyBase2 class is also marked as abstract you should tell the compiler that GetValue() is implemented in this class instead of other class(es) higher in hierarchy (implementing MyBase2)

Upvotes: 1

Stefan
Stefan

Reputation: 17678

Why do I have to specify override for MyBase2.GetValue()?

This is a paradigm which has been adopted by c++ as well.

The idea is: by explitly having the need to use the keywords override for virtual and abstract, you will ensure that you're not making a typo when doing the override. Because if you would mot see such a typo, the behaviour, escpecially on virtual would change significantly.

Having said that; I still find it strange that the new keyword for added methods is still optional and only emits a warning when omitted.

Upvotes: 4

Related Questions