If in a derived class you can override both a concrete method and an abstract method of an abstract parent class,then what's the point of having abstract methods in the first place?
If for example there in the parent class there is a concrete method called 'display' that just prints 'hi from the base class' which can be overridden in the derived class to print 'hi from the derived class',what would the difference be if the 'display' method in the parent would be abstract instead of veing concrete? It would be overridden too in any case.
CodePudding user response:
The difference is simple: An abstract method must be overridden. When you have a non-abstract (virtual) method you can decide that you don't want to override it in a derived class. So the programmer of the base class can decide whether any derived class must override the method or can override the method.
C# and java differ in what is the default for "overridability". In java, methods are by default virtual and can be overridden, in C#, the default is that methods are not virtual, unless explicitly declared so. But both languages have all three concepts: abstract methods (these must be overridden), virtual methods (these can be overridden) and final/sealed methods (these cannot be overridden).
CodePudding user response:
If you mean the difference between abstract
method and a virtual
method in the base class: the difference is simply that the abstract
one must be overridden, i.e. there is no meaningful base implementation, and a custom implementation must be provided for the type to be valid - whereas a virtual
method can optionally be overridden if the inheritor wishes.
CodePudding user response:
You use abstract class when not all methods can be implemented in a default way. For example Shape class as base class and derived Rectangle and Circle. Last two will implement Draw method but parent/base class what should do in a Draw method?
Use virtual if method has default implementation and abstract if it has not.
CodePudding user response:
As PMF mentioned, abstract methods must be overridden while concrete can be overridden.
The difference must also be understood in the context of hierarchy where one abstract class can be extended by (parent of) multiple other classes.
The concrete method definition in the abstract class provides a default implementation that is generally acceptable by many child class implementations but can also be overridden in case a different implementation is required.
But the abstract method must always be overridden by all the child classes.