I'm reading the excerpt below from Joe Albahari's excellent "C# 9 in a Nutshell" and am trying to understand what's being described here in bold. Is anyone able to explain the alternative approach in a way that I can understand better? This seems somewhat backward to me for some reason.
Alternatives to interface reimplementation
Even with explicit member implementation, interface reimplementation is problematic for a couple of reasons:
The subclass has no way to call the base class method.
The base class author might not anticipate that a method be reimplemented and might not allow for the potential consequences.
Reimplementation can be a good last resort when subclassing hasn’t been anticipated. A better option, however, is to design a base class such that reimplementation will never be required. There are two ways to achieve this:
When implicitly implementing a member, mark it virtual if appropriate.
When explicitly implementing a member, use the following pattern if you anticipate that subclasses might need to override any logic:
public class TextBox : IUndoable
{
void IUndoable.Undo() => Undo(); // Calls method below
protected virtual void Undo() => Console.WriteLine ("TextBox.Undo");
}
public class RichTextBox : TextBox
{
protected override void Undo() => Console.WriteLine("RichTextBox.Undo");
}
If you don’t anticipate any subclassing, you can mark the class as sealed to preempt interface reimplementation.
The issue described, is that when a base class implements an interface, that base class may expect certain behaviour to occur.
The example of the textbox undo. Suppose that the base textbox does something important (or perhaps the actual work) for undoing.
Also for the sake of example, assumen that when writing the base class, the author did not think of inheriting classes (richtextbox here)
He could have written it as
public class TextBox : IUndoable
{
void IUndoable.Undo() => ....... undo logic here
}
Any inheriting class would not be able to call Undo directly (they would have to cast its base to IUndoable )
The problem now is, when other code, use the IUndo implementation (for example a menu item), the important undo in the base class would not be called, unless the inheriting class does this explicitely
Still the same with:
public class TextBox : IUndoable
{
public void Undo() => ...... undo logic here
}
The inheriting (RichTextBox) class, could call its base when explicitly implementing Undo, but it wouldn't be sure.
If RichTextBox makes its own Undo and hides the base Undo, there is no direct impulse to call the base Undo (Although more so than the first option)
In the end, what the base class author wants, is that when external code calls the IUndoable.Undo method, the required code is always called.
(Side note: In an abstract class that could be handled differently, but this is a directly usable class, that may or may not be inherited)
Making the implicit implementation virtual helps a bit:
public class TextBox : IUndoable
{
public virtual void Undo() => ...... undo logic here
}
As soon as an inheriting class overrides the method, the default snippet also calls the base class, but that is assuming the snippet is used, and base.Undo still is called, leaving the option to the inheritor.
That gives the last example as you included it:
public class TextBox : IUndoable
{
void IUndoable.Undo() => Undo(); // Calls method below
protected virtual void Undo() => Console.WriteLine ("TextBox.Undo");
}
This gives a more secure option for inheriting classes to implement their own undo, without losing the undo of the base class (unless the inheriting class explicitly implements IUndoable as well, but let's not go there :P )
In the richtextbox example, the Undo is overriden, but the base Undo is not called. Exactly the sort of situation that could cause the base class implementation of 'undo' to be skipped.
But here, if something (a menu item for example) calls Undo of IUndoable the explicit implementation is called, forcing the required base class undo functionality to run, but also the overriden implementation of the inheriting class (richtextbox)
As I understood, what the author wants to say is that instead of hiding members of the base class, override them. Hiding is when child class has a member with the same signature, yet it's not marked virtual in the base class.
i.e. if ParentClass has method A(); If you want it to be overridden by ChildClass, make A() a virtual method. Or if you don't want A() to be overridden, introduce a protected method, that A() will use and make that protected method virtual for childs to override if needed.
Hope this answers your question.
Is anyone able to explain the alternative approach in a way that I can
understand better?
All it is saying is that if you try and do my below code it won't compile.
So then what are you to do if you need to use explicit interface implementation and an inheriting class needs to alter that behaviour? Well, you use the exact code you mentioned in your question. It allows you to use explicit interface implementation and allow it to be overriden.
That is it. That is all it is saying.
using System;
public interface IUndoable {
void Undo();
}
public class TextBox : IUndoable
{
void IUndoable.Undo() => Console.WriteLine ("TextBox.Undo");
}
public class RichTextBox : TextBox
{
void IUndoable.Undo() => Console.WriteLine ("RichTextBox.Undo");
}
public class Program
{
public static void Main()
{
}
}
I'm trying to find a proper way to restrict/force the usage of methods in order to ensure the correct internal handling.
Given the following abstract base class
public abstract class BaseClass
{
// needs to be overriden by concrete implementation
protected abstract void CreateInternal(object dataToCreate);
// only visible method
public void Create(object dataToCreate)
{
// check the data provided <-- this is important to be done each time
CheckData(dataToCreate);
// call implementation of concrete class
CreateInternal(dataToCreate);
}
private void CheckData(object dataToCheck)
{
if(dataToCheck == null) throw new Exception("Data is not valid");
}
}
and a simple implementation
public class ChildClass : BaseClass
{
protected override void CreateInternal(object dataToCreate)
{
// do create-stuff related to ChildClass
}
}
My question: Is there a way to restrict the access to CreateInternal? In ChildClass I could create a public method
public void DoStuff(object dataToDoStuff)
{
// access protected method is not forbidden
CreateInternal(dataToDoStuff);
}
This will call CreateInternal without doing the needed checks as if it would do if called via Create of the base-class.
Is there any way to force the usage of Create prior to CreateInternal? There is no need to have this at compile-time (but it would be nice), but at least at runtime.
I have something like checking who is calling in mind.
public class ChildClass : BaseClass
{
protected override void CreateInternal(object dataToCreate)
{
// if not called via base 'Create' -> throw exception
}
}
Is there some pattern I'm not aware of or is what I'm trying to achieve too weired and simply not possible?
There is no way of really enforcing this at compile or runtime. As you well say, a virtual protected method is reachable and overridable from any derived type so you'd always have to rely on the implementation of the overriden method making the necessary checks which kind of defeats the purpose.
IMHO your best bet is to enforce this through code reviews if you can control who's extending your class. If thats not the case then, seeing that your Create method is not virtual and is simply changing the state of BaseClass, why don't you call it in the constructor? Is this possible or is your example a simplified scenario and this isn't an option? Doing this would guarantee that Create is always called first.
UPDATE: Contrary to what I said before, there are "ways" you could enforce this at runtime.
Although not shown in your example, I'm guessing there will be some kind of internal state in BaseClass that any derived class must leverage via methods, properties, fields, etc. to be of any use (inheritance would be kind of pointless otherwise). You could always set a private flag createCalled in BaseClass and make all BaseClass methods, getters (yuck) and setters check the flag and bail out with an InvalidOperationException if its not set. This would esentially render useless any derived instance not correctly initialized. Ugly but doable.
Or even simpler, if you control all potential consumers of BaseClass and any derived type out there in the wild, then just make the flag public public bool Initialized { get; }and check when consuming the object and bail out if necessary.
"Weird" would not be the word of choice of mine, but still..
As far as I can see, what you are trying to achieve is to prevent the ChildClass owner, who implemented CreateInternal()'s method body, from executing those statements without invoking CheckData() first.
Even if this works, he can still copy and paste the statements into DoStuff() method body and can execute them there.
We do not force, we guide.
People will follow your guideline, and they will be happy to see that their class is working according to it.
Often, in C# documentation, you come across a member where the description says something along the lines of "be sure to call the base method if you override this."
Is there a way to ensure at compile time that one has actually called the base function?
Here's an example:
Implementing a Dispose Method
From the first lines:
A type's Dispose method should release
all the resources that it owns. It
should also release all resources
owned by its base types by calling its
parent type's Dispose method.
EDIT
I was browsing, and I came across this article, which seems rather relevant. It's more of a small than an error, ie. it has valid uses (such as those mentioned):
Call Super
You can't enforce it, but you can do it via a call like base.Foo(bar). base allows you to access members of the class you're inheriting from.
You can kind of enforce this behavior by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritence (e.g. class Dachsund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
You can call it like this:
public override void MyFunction()
{
// do dome stuff
SomeStuff();
// call the base implementation
base.MyFunction();
}
But if you're asking whether it can be "checked" at compile time - no.
You could probably use a dependency analysis tool such as NDepend to create rules to check this is being done, and have the rules run as part of the compile, but I don't think you can do the enforecement from the compiler itself.
A common pattern for a single level of inheritance is to provide a non-virtual template method with a virtual extension point.
protected virtual void ExtensionPoint () { }
public void TemplateMethod () {
ExtensionPoint();
ThisWillAlwaysGetCalled();
}
If all calls to the operation call the template method, then any override of the extension point will be called, along with the code in the template method which will always get called.
I have an abstract class in a library. I'm trying to make it as easy as possible to properly implement a derivation of this class. The trouble is that I need to initialize the object in a three-step process: grab a file, do a few intermediate steps, and then work with the file. The first and last step are particular to the derived class. Here's a stripped-down example.
abstract class Base
{
// grabs a resource file specified by the implementing class
protected abstract void InitilaizationStep1();
// performs some simple-but-subtle boilerplate stuff
private void InitilaizationStep2() { return; }
// works with the resource file
protected abstract void InitilaizationStep3();
protected Base()
{
InitilaizationStep1();
InitilaizationStep2();
InitilaizationStep3();
}
}
The trouble, of course, is the virtual method call in the constructor. I'm afraid that the consumer of the library will find themselves constrained when using the class if they can't count on the derived class being fully initialized.
I could pull the logic out of the constructor into a protected Initialize() method, but then the implementer might call Step1() and Step3() directly instead of calling Initialize(). The crux of the issue is that there would be no obvious error if Step2() is skipped; just terrible performance in certain situations.
I feel like either way there is a serious and non-obvious "gotcha" that future users of the library will have to work around. Is there some other design I should be using to achieve this kind of initialization?
I can provide more details if necessary; I was just trying to provide the simplest example that expressed the problem.
I would consider creating an abstract factory that is responsible for instantiating and initializing instances of your derived classes using a template method for initialization.
As an example:
public abstract class Widget
{
protected abstract void InitializeStep1();
protected abstract void InitializeStep2();
protected abstract void InitializeStep3();
protected internal void Initialize()
{
InitializeStep1();
InitializeStep2();
InitializeStep3();
}
protected Widget() { }
}
public static class WidgetFactory
{
public static CreateWidget<T>() where T : Widget, new()
{
T newWidget = new T();
newWidget.Initialize();
return newWidget;
}
}
// consumer code...
var someWidget = WidgetFactory.CreateWidget<DerivedWidget>();
This factory code could be improved dramatically - especially if you are willing to use an IoC container to handle this responsibility...
If you don't have control over the derived classes, you may not be able to prevent them from offering a public constructor that can be called - but at least you can establish a usage pattern that consumers could adhere to.
It's not always possible to prevent users of you classes from shooting themselves in the foot - but, you can provide infrastructure to help consumers use your code correctly when they familiarize themselves with the design.
That's way too much to place in the constructor of any class, much less of a base class. I suggest you factor that out into a separate Initialize method.
In lots of cases, initialization stuff involves assigning some properties. It's possible to make those properties themselves abstract and have derived class override them and return some value instead of passing the value to the base constructor to set. Of course, whether this idea is applicable depends on the nature of your specific class. Anyway, having that much code in the constructor is smelly.
At first sight, I would suggest to move this kind of logic to the methods relying on this initialization. Something like
public class Base
{
private void Initialize()
{
// do whatever necessary to initialize
}
public void UseMe()
{
if (!_initialized) Initialize();
// do work
}
}
Since step 1 "grabs a file", it might be good to have Initialize(IBaseFile) and skip step 1. This way the consumer can get the file however they please - since it is abstract anyways. You can still offer a 'StepOneGetFile()' as abstract that returns the file, so they could implement it that way if they choose.
DerivedClass foo = DerivedClass();
foo.Initialize(StepOneGetFile('filepath'));
foo.DoWork();
Edit: I answered this for C++ for some reason. Sorry. For C# I recommend against a Create() method - use the constructor and make sure the objects stays in a valid state from the start. C# allows virtual calls from the constructor, and it's OK to use them if you carefully document their expected function and pre- and post-conditions. I inferred C++ the first time through because it doesn't allow virtual calls from the constructor.
Make the individual initialization functions private. The can be both private and virtual. Then offer a public, non-virtual Initialize() function that calls them in the correct order.
If you want to make sure everything happens as the object is created, make the constructor protected and use a static Create() function in your classes that calls Initialize() before returning the newly created object.
You could employ the following trick to make sure that initialization is performed in the correct order. Presumably, you have some other methods (DoActualWork) implemented in the base class, that rely on the initialization.
abstract class Base
{
private bool _initialized;
protected abstract void InitilaizationStep1();
private void InitilaizationStep2() { return; }
protected abstract void InitilaizationStep3();
protected Initialize()
{
// it is safe to call virtual methods here
InitilaizationStep1();
InitilaizationStep2();
InitilaizationStep3();
// mark the object as initialized correctly
_initialized = true;
}
public void DoActualWork()
{
if (!_initialized) Initialize();
Console.WriteLine("We are certainly initialized now");
}
}
I wouldn't do this. I generally find that doing any "real" work in a constructor ends up being a bad idea down the road.
At the minimum, have a separate method to load the data from a file. You could make an argument to take it a step further and have a separate object responsible for building one of your objects from file, separating the concerns of "loading from disk" and the in-memory operations on the object.
What is the difference between an abstract method and a virtual method? In which cases is it recommended to use abstract or virtual methods? Which one is the best approach?
An abstract function cannot have functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.
A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.
An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.
A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.
So for example:
public abstract class myBase
{
//If you derive from this class you must implement this method. notice we have no method body here either
public abstract void YouMustImplement();
//If you derive from this class you can change the behavior but are not required to
public virtual void YouCanOverride()
{
}
}
public class MyBase
{
//This will not compile because you cannot have an abstract method in a non-abstract class
public abstract void YouMustImplement();
}
Only abstract classes can have abstract members.
A non-abstract class that inherits from an abstract class must override its abstract members.
An abstract member is implicitly virtual.
An abstract member cannot provide any implementation (abstract is called pure virtual in some languages).
You must always override an abstract function.
Thus:
Abstract functions - when the inheritor must provide its own implementation
Virtual - when it is up to the inheritor to decide
Abstract Function:
It can be declared only inside abstract class.
It contains only
method declaration not the implementation in abstract class.
It must be overridden in derived class.
Virtual Function:
It can be declared inside abstract as well as non abstract class.
It contains method implementation.
It may be overridden.
explanation: with analogies. hopefully it will help you.
Context
I work on the 21 st floor of a building. And I'm paranoid about fire. Every now and again, somewhere in the world, a fire is burning down a sky scraper. But luckily we have an instruction manual somewhere here on what to do in case of fire:
FireEscape()
Don't collect belongings
Walk to fire escape
Walk out of building
This is basically a virtual method called FireEscape()
Virtual Method
This plan is pretty good for 99% of the circumstances. It's a basic plan which works. But there is a 1% chance that the fire escape is blocked or damaged in which case you are completely screwed and you'll become toast unless you take some drastic action. With virtual methods you can do just that: you can override the basic FireEscape() plan with your own version of the plan:
Run to window
Jump out the window
Parachute safely to the bottom
In other words virtual methods provide a basic plan, which can be overriden if you need to. Subclasses can override the parent class' virtual method if the programmer deems it appropriate.
Abstract methods
Not all organisations are well drilled. Some organisations don't do fire drills. They don't have an overall escape policy. Every man is for himself. Management are only interested in such a policy existing.
In other words, each person is forced to develop his own FireEscape() method. One guy will walk out the fire escape. Another guy will parachute. Another guy will use rocket propulsion technology to fly away from the building. Another guy will abseil out. Management don't care how you escape, so long as you have a basic FireEscape() plan - if they don't you can be guaranteed OHS will come down on the organisation like a tonne of bricks. This is what is meant by an abstract method.
What's the difference between the two again?
Abstract method: sub classes are forced to implement their own FireEscape method. With a virtual method, you have a basic plan waiting for you, but can choose to implement your own if it's not good enough.
Now that wasn't so hard was it?
Abstract method:
When a class contains an abstract method, that class must be declared as abstract.
The abstract method has no implementation and thus, classes that derive from that abstract class, must provide an implementation for this abstract method.
Virtual method:
A class can have a virtual method. The virtual method has an implementation.
When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.
When to use what:
In some cases, you know that certain types should have a specific method, but, you don't know what implementation this method should have.
In such cases, you can create an interface which contains a method with this signature.
However, if you have such a case, but you know that implementors of that interface will also have another common method (for which you can already provide the implementation), you can create an abstract class.
This abstract class then contains the abstract method (which must be overriden), and another method which contains the 'common' logic.
A virtual method should be used if you have a class which can be used directly, but for which you want inheritors to be able to change certain behaviour, although it is not mandatory.
An abstract method is a method that must be implemented to make a concrete class. The declaration is in the abstract class (and any class with an abstract method must be an abstract class) and it must be implemented in a concrete class.
A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. If you don't override, you get the original behavior. If you do, you always get the new behavior. This opposed to not virtual methods, that can not be overridden but can hide the original method. This is done using the new modifier.
See the following example:
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
When I instantiate DerivedClass and call SayHello, or SayGoodbye, I get "Hi There" and "See you later". If I call HelloGoodbye, I get "Hello" and "See you later". This is because SayGoodbye is virtual, and can be replaced by derived classes. SayHello is only hidden, so when I call that from my base class I get my original method.
Abstract methods are implicitly virtual. They define behavior that must be present, more like an interface does.
Abstract methods are always virtual. They cannot have an implementation.
That's the main difference.
Basically, you would use a virtual method if you have the 'default' implementation of it and want to allow descendants to change its behaviour.
With an abstract method, you force descendants to provide an implementation.
I made this simpler by making some improvements on the following classes (from other answers):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestOO
{
class Program
{
static void Main(string[] args)
{
BaseClass _base = new BaseClass();
Console.WriteLine("Calling virtual method directly");
_base.SayHello();
Console.WriteLine("Calling single method directly");
_base.SayGoodbye();
DerivedClass _derived = new DerivedClass();
Console.WriteLine("Calling new method from derived class");
_derived.SayHello();
Console.WriteLine("Calling overrided method from derived class");
_derived.SayGoodbye();
DerivedClass2 _derived2 = new DerivedClass2();
Console.WriteLine("Calling new method from derived2 class");
_derived2.SayHello();
Console.WriteLine("Calling overrided method from derived2 class");
_derived2.SayGoodbye();
Console.ReadLine();
}
}
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye\n");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public abstract class AbstractClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
//public virtual void SayGoodbye()
//{
// Console.WriteLine("Goodbye\n");
//}
public abstract void SayGoodbye();
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
public class DerivedClass2 : AbstractClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
// We should use the override keyword with abstract types
//public new void SayGoodbye()
//{
// Console.WriteLine("See you later2");
//}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
}
Binding is the process of mapping a name to a unit of code.
Late binding means that we use the name, but defer the mapping. In other words, we create/mention the name first, and let some subsequent process handle the mapping of code to that name.
Now consider:
Compared to humans, machines are really good at searching and sorting
Compared to machines, humans are really good at invention and innovation
So, the short answer is: virtual is a late binding instruction for the machine (runtime) whereas abstract is the late binding instruction for the human (programmer)
In other words, virtual means:
“Dear runtime, bind the appropriate code to this name by doing what you do best: searching”
Whereas abstract means:
“Dear programmer, please bind the appropriate code to this name by doing what you do best: inventing”
For the sake of completeness, overloading means:
“Dear compiler, bind the appropriate code to this name by doing what you do best: sorting”.
You basically use a virtual method when you want the inheritors to extend the functionality IF they want to.
You use abstract methods when you want the inheritors to implement the functionality (and in this case they have no choice)
Virtual Method:
Virtual means we CAN override it.
Virtual Function has an implementation. When we inherit the class we
can override the virtual function and provide our own logic.
We can change the return type of Virtual function while implementing the
function in the child class(which can be said as a concept of
Shadowing).
Abstract Method
Abstract means we MUST override it.
An abstract function has no implementation and must be in an abstract class.
It can only be declared. This forces the derived class to provide the implementation of it.
An abstract member is implicitly virtual. The abstract can be called as pure virtual in some of the languages.
public abstract class BaseClass
{
protected abstract void xAbstractMethod();
public virtual void xVirtualMethod()
{
var x = 3 + 4;
}
}
I have seen in some places the abstract method is defined as below. **
"An Abstract Method must have to implement in the child class"
**
I felt it is like .
It is not necessary that an abstract method has to be implemented in a child class, if the child class is also abstract ..
1)An abstract method cant be a private method.
2)An Abstract method cant be implemented in the same abstract class.
I would say ..if we are implementing an abstract class, you must have to override the abstract methods from the base abstract class.
Because.. Implementing the abstract method is with override key word .Similar to Virtual method.
It is not necessary for a virtual method to be implemented in an inherited class.
----------CODE--------------
public abstract class BaseClass
{
public int MyProperty { get; set; }
protected abstract void MyAbstractMethod();
public virtual void MyVirtualMethod()
{
var x = 3 + 4;
}
}
public abstract class myClassA : BaseClass
{
public int MyProperty { get; set; }
//not necessary to implement an abstract method if the child class is also abstract.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}
public class myClassB : BaseClass
{
public int MyProperty { get; set; }
//You must have to implement the abstract method since this class is not an abstract class.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}
Most of the above examples use code - and they are very very good. I need not add to what they say, but the following is a simple explanation that makes use of analogies rather than code/technical terms.
Simple Explanation - Explanation using analogies
Abstract Method
Think George W Bush. He says to his soldiers: "Go fight in Iraq". And that's it. All he has specified is that fighting must be done. He does not specify how exactly that will happen. But I mean, you can't just go out and "fight": what does that mean exactly? do I fight with a B-52 or my derringer? Those specific details are left to someone else. This is an abstract method.
Virtual Method
David Petraeus is high up in the army. He has defined what fight means:
Find the enemy
Neutralise him.
Have a beer afterwards
The problem is that it is a very general method. It's a good method that works, but sometimes is not specific enough. Good thing for Petraeus is that his orders have leeway and scope - he has allowed others to change his definition of "fight", according to their particular requirements.
Private Job Bloggs reads Petraeus' order and is given permission to implement his own version of fight, according to his particular requirements:
Find enemy.
Shoot him in the head.
Go Home
Have beer.
Nouri al Maliki also receives the same orders from Petraeus. He is to fight also. But he is a politician, not an infantry man. Obviously he cannot go around shooting his politican enemies in the head. Because Petraeus has given him a virtual method, then Maliki can implement his own version of the fight method, according to his particular circumstances:
Find enemy.
Have him arrested with some BS trumped up charges.
Go Home
Have beer.
IN other words, a virtual method provides boilerplate instructions - but these are general instructions, which can be made more specific by people down the army heirarchy, according to their particular circumstances.
The difference between the two
George Bush does not prove any implementation details. This must be provided by someone else. This is an abstract method.
Petraeus on the other hand does provide implementation details but he has given permission for his subordinates to override his orders with their own version, if they can come up with something better.
hope that helps.
Abstract function(method) :
● An abstract method is a method which is declared with the keyword abstract.
● It does not have body.
● It should be implemented by the derived class.
● If a method is abstract then the class should abstract.
virtual function(method) :
● A virtual method is the method which is declared with the keyword virtual and it can be overridden by the derived class method by using override keyword.
● It's up to the derived class whether to override it or not.
The answer has been provided a number of times but the the question about when to use each is a design-time decision. I would see it as good practice to try to bundle common method definitions into distinct interfaces and pull them into classes at appropriate abstraction levels. Dumping a common set of abstract and virtual method definitions into a class renders the class unistantiable when it may be best to define a non-abstract class that implements a set of concise interfaces. As always, it depends on what best suits your applications specific needs.
Abstract function cannot have a body and MUST be overridden by child classes
Virtual Function will have a body and may or may not be overridden by child classes
From general object oriented view:
Regarding abstract method: When you put an abstract method in the parent class actually your are saying to the child classes: Hey note that you have a method signature like this. And if you wanna to use it you should implement your own!
Regarding virtual function: When you put a virtual method in the parent class you are saying to the derived classes : Hey there is a functionality here that do something for you. If this is useful for you just use it. If not, override this and implement your code, even you can use my implementation in your code !
this is some philosophy about different between this two concept in General OO
An abstract function is "just" a signature, without an implementation.
It is used in an interface to declare how the class can be used.
It must be implemented in one of the derived classes.
Virtual function (method actually), is a function you declare as well, and should implemented in one of the inheritance hierarchy classes.
The inherited instances of such class, inherit the implementation as well, unless you implement it, in a lower hierarchy class.
From a C++ background, C# virtual corresponds to C++ virtual, while C# abstract methods corresponds to C++ pure virtual function
If a class derives from this abstract class, it is then forced to override the abstract member. This is different from the virtual modifier, which specifies that the member may optionally be overridden.
There are nothing call virtual class in C#.
For functions
Abstract function only have signature only,the drive class should override with functionality.
Virtual function will hold the part of functionality the drive class may or may not override it according to the requirement
You can decide with your requirement.
Abstract method doesnt have an implementation.It is declared in the parent class. The child class is resposible for implementing that method.
Virtual method should have an implementation in the parent class and it facilitates the child class to make the choice whether to use that implementation of the parent class or to have a new implementation for itself for that method in child class.
An abstract function or method is a public "operation's name" exposed by a class, its aim, along with abstract classes, is primarily provide a form of constraint in objects design against the structure that an object have to implement.
In fact the classes that inherit from its abstract class have to give an implementation to this method, generally compilers raise errors when they don't.
Using abstract classes and methods is important mostly to avoid that by focusing on implementation details when designing classes, the classes structure be too related to the implementations, so creating dependences and coupling between classes that collaborate among them.
A virtual function or method is simply a method that models a public behaviour of a class, but that we can leave free to modify it in the inheritance chain, because we think that child classes could have need to implement some specific extensions for that behaviour.
They both represent a form of polymorpfhism in object orientation paradigm.
We can use abstract methods and virtual functions together to support a good inheritance model.
We design a good abstract structure of main objects of our solution, then create basic implementations by locating those more prone to further specializations and we make these ones as virtuals, finally we specialize our basic implementations, eventyually "overriding" inherited virtual ones.
Here I am writing some sample code hoping this may be a rather tangible example to see the behaviors of the interfaces, abstract classes and ordinary classes on a very basic level. You can also find this code in github as a project if you want to use it as a demo: https://github.com/usavas/JavaAbstractAndInterfaceDemo
public interface ExampleInterface {
// public void MethodBodyInInterfaceNotPossible(){
// }
void MethodInInterface();
}
public abstract class AbstractClass {
public abstract void AbstractMethod();
// public abstract void AbstractMethodWithBodyNotPossible(){
//
// };
//Standard Method CAN be declared in AbstractClass
public void StandardMethod(){
System.out.println("Standard Method in AbstractClass (super) runs");
}
}
public class ConcreteClass
extends AbstractClass
implements ExampleInterface{
//Abstract Method HAS TO be IMPLEMENTED in child class. Implemented by ConcreteClass
#Override
public void AbstractMethod() {
System.out.println("AbstractMethod overridden runs");
}
//Standard Method CAN be OVERRIDDEN.
#Override
public void StandardMethod() {
super.StandardMethod();
System.out.println("StandardMethod overridden in ConcreteClass runs");
}
public void ConcreteMethod(){
System.out.println("Concrete method runs");
}
//A method in interface HAS TO be IMPLEMENTED in implementer class.
#Override
public void MethodInInterface() {
System.out.println("MethodInInterface Implemented by ConcreteClass runs");
// Cannot declare abstract method in a concrete class
// public abstract void AbstractMethodDeclarationInConcreteClassNotPossible(){
//
// }
}
}
Figure. — Traditional threefold classification of propositions.
In deontic logic (the study of obligation and permission), every proposition is obligatory (‘must’ operator), optional (‘may and may not’ operator), or impermissible (‘must not’ operator), and no proposition falls into more than one of these three categories.
Furthermore, the permissible (‘may’ operator) propositions are those that are obligatory or optional, the omissible (‘may not’ operator) propositions are those that are impermissible or optional, and the non-optional (‘must or must not’ operator) propositions are those that are obligatory or impermissible.
In particular, an obligatory proposition is permissible, and an impermissible proposition is omissible.
Applying those operators to the proposition ’the method is overridden’ yields the following propositions:
abstract (pure)/concrete method: the method must be overridden/may not be overridden;
virtual/real (final) method: the method may be overridden/must not be overridden.
In particular, an abstract method is virtual, and a real method is concrete.
To my understanding:
Abstract Methods:
Only the abstract class can hold abstract methods. Also the derived class need to implement the method and no implementation is provided in the class.
Virtual Methods:
A class can declare these and also provide the implementation of the same. Also the derived class need to implement of the method to override it.