Adding private method to class by inheritance in C# - c#

I asked this question yesterday, but I think it was unclear what my primary concern was. In C++, we have private and multiple inheritance, which enables us to add private methods to classes by just inheriting from the class declaring these methods. That is, if there's a class
class B {
public:
virtual void doMethodB();
};
and a class
class A : private B {
virtual int doMethodA();
};
doMethodB() can be called from within doMethodA(), but is not accessible from outside.
Now, I'd like to mimic this behavior in C#. There is no multiple nor private inheritance. Up to know, I can think of four way to achieve somthing similar, but still with serious drawbacks:
First: Use an interface, i.e.
interface IB {
public void doMethodB();
};
class A : IB {
public void doMethodB();
int doMethodA();
};
However, when we do this, doMethodB() is public, and must be implemented in each class inheriting from IB.
Second: Use a static method
public static class B {
public static void doMethodB();
};
That way, there need only be one implementation, but the method is still public and can't be restricted to certain classes.
Third: Use a extension method, like that. That way however, the method is called on the object (i.e. a.doMethodB()) and not from "inside".
Fourth: Composition.
class A {
private B b;
public int doMethodA();
};
Now, B's methods can be called like b.doMethodB() from A only, but are other issues now regarding serialization, b == null etc.
Is there another alternative? And if not, which one among the presented ones would you consider "the best"?

Regarding your "First" proposal with interfaces: you can also implement the interface explicitly:
"A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. "
See / Source: http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx
However, i would choose the Composition approach. "Favor Composition over Inheritance", also see Prefer composition over inheritance?
Ideally, i would constructor-inject B into A by dependency injection, that should help mitigate your b == null concern.
Note:
Using a static method / extension method (is a static method, too...) makes unit-testing A (respectively faking B) very hard, which is why i would forgo these solutions completely.
Edit:
If you don't need B.doMethodB accessible from anyone else than A, you can also make B an abstract class and B.doMethodB a protected method.
But i was thinking that you already know that ;-)
(And because of the testing issues i would still favor composition over inheritance).

I think the concept you are looking for is the protected access modifier. It means that only B itself and its derived classes can access the method, but others cannot.
class B {
protected virtual void DoMethodB() {}
}
class A : B {
virtual void DoMethodA() {
DoMethodB();
}
}
If you wanted, you can further restrict the access to protected internal which means that the method can only be accessed from derived classes inside your assembly.
Also, be aware of the consequences of virtual methods. If there is no explicit need to make a method virtual, it should not be marked virtual.

Related

How to understand which class uses composition?

I don't understand the difference between these cases of "composition" in c#, could anyone explain?
class B
{
}
example 1:
class A : IDisposable
{
private B objB;
public A(){objB = new B();}
public void Dispose(){}
}
example 2:
class A : IDisposable
{
private B objB;
public A(B obj){this.objB = obj;}
public void Dispose(){}
}
example 3:
class A : IDisposable
{
private B objB;
public A(){}
public void Sample(){objB = new B();}
public void Dispose(){}
}
I know that one is not the composition, but I don't understand why.
Also, is there a difference in cases:
class B : IDisposable
{
//is there a difference if I will and won't implement the methods of the interface?
}
class A : IDisposable
{
public B objB {get;set;}
public A(){}
public void Sample(){}
public void Dispose(){}
}
So my questions about composition: 1) Is there a difference if the B in A is private or public? 2) Do I have to initialize the B in A to count it as a composition? If so, is there any difference in what way I will do this? 3) Can I use composition if both my classes implement the same interface, but one of them doesn't implement its methods? (the last example).
Thanks for the answers!
All are examples of composition, at least in the sense of composition vs inheritance. A useful memonic is that composition has a and inheritance is a. I.e. A has a B. On the other hand A is a IDisposable.
There is also composition vs aggregation. In this sense composition owns a while aggregation uses a. Example 1 and 3 are clear examples of ownership. For example 2 it is unclear, in some cases a constructor parameter might imply taking ownership of the object, in other cases it might not, and in some cases there is a separate parameter to decide if ownership should be transferred or not. In any case, "Ownership" usually only matters if the the object is IDisposable, so in this trivial example it is not really useful to talk aggregation vs composition.
The examples rather show different way to take dependencies, if the object B is required for the correct functioning of the object A, then A depends on B.
Example 1 is simply creating its dependency, and is typical when depending on 'simple' objects, like a list.
Example 2 can be called dependency injection, and is usually a good idea for more complex object hierarchies.
Example 3 could be called Initialization. I.e. your Sample-method is initializing the object, and must be called before the object can be used. I would try to avoid this, since it is easy to forget to call the initialization method. It is typically easier
Your last example would be of an optional property. I.e. A should work just fine if objB is not set by anyone, but may change its behavior if it is set.
To me this is a rater poor question. I do not think I have ever discussed composition vs aggregation, and composition vs inheritance is usually mentioned to advocate against inheritance. I suspect the real point is regarding lifetimes and disposal. Any disposable object needs to be disposed, and it should always be clear who is responsible for disposing the object. A somewhat common pattern is something like this:
public class MyClass : IDisposable{
public MyDependency dep;
public suppressDispose;
public MyClass(MyDependency dep, bool suppressDispose = false) => (dep, suppressDispose ) = (dep, suppressDispose );
public void Dispose(){
if(!suppressDispose) dep.Dispose();
}
}
That takes over ownership by default, but allow for an opt out if the dependency need to be used later.

C# private (hidden) base class

Is it possible to make a C# base class accessible only within the library assembly it's compiled into, while making other subclasses that inherit from it public?
For example:
using System.IO;
class BaseOutput: Stream // Hidden base class
{
protected BaseOutput(Stream o)
{ ... }
...lots of common methods...
}
public class MyOutput: BaseOutput // Public subclass
{
public BaseOutput(Stream o):
base(o)
{ ... }
public override int Write(int b)
{ ... }
}
Here I'd like the BaseOutput class to be inaccessible to clients of my library, but allow the subclass MyOutput to be completely public. I know that C# does not allow base classes to have more restrictive access than subclasses, but is there some other legal way of achieving the same effect?
UPDATE
My solution for this particular library is to make the base class public and abstract, and to document it with "Do not use this base class directly". I also make the constructor of the base class internal, which effectively prevents outside clients from using or inheriting the class.
(It's a shame, because other O-O languages let me have hidden base classes.)
Unfortunately not. You can't derive a public class from an internal or private class.
You need to either expose the base class, or you need to declare all the methods for all of your similar classes. If you go the route where you declare all methods again, it's probably useful to create a helper class, which has the actual implementation of them. Still it's quite a bit of boilerplate.
Consider a pattern such as a Facade. That's what they're there for. I don't think you can achieve what you require with straight inheritance.
Depending on what "lot of common methods" are doing you may achieve some of it with internal extension methods:
internal static class MyStreamExtensions
{
internal static int UsefulOne(this Stream stream)
{
return 42;
}
}
Another approach is to make constructor internal to prevent unintentional derivation from that class:
public class BaseOutput: Stream
{
internal BaseOutput(Stream o)
{ ... }
...lots of common methods...
}
This will make code more understandable compared to "not-really-visible" intermediate class in hierarchy.

interface & inheritance

C#, VS 2008
I have 4 cases say a,b,c,d, I plan to seperate them and create seperate classes
the 4 cases have something in common, I put them in an interface and create a base class that implement the interface. now there are something in common between a&b, a&c, c&d, not sure how to make a good/clean implement
thanks
There are several options.
You could have c and d inherit from a, and d inherit from c.
You could create a base class for each pair a/b, a/c, and c/d.
You could duplicate functionality.
You could provide the functionality via a helper class (static methods might be an option).
It really depends on what functionality is being shared, and the intended usage of the classes.
It depends on how the common things works and how they relate to and use private/protected data, but often composition can be a complement or alternative to inheritance.
Break out the common parts to helper classes that you use from the different implementations of a,b,c and d.
This is only possible if the implementation is not tightly coupled to the private data of each class.
As a general rule, you should only use inheritance if your objects are different kinds of the same object. If this is the case, then you can use inheritance to share implementation that's inherent in the definition of the base object.
If classes a,b,c and d aren't really different kinds of the same object then you can try encapsulating their common functionality in an internally referenced object.
public class a
{
private CommonFunctionalityClass commonFunc;
public a()
{
this.commonFunc = new CommonFunctionalityClass();
}
}
When you want to do the common stuff, you just call your instance of commonFunc. You can do this same encapsulation for a/b, b/c, and c/d where you share functionality via a has a relationship using an internally referenced object. That way you don't duplicate code, but you can share functionality flexibly.
public interface IABInterface
{
//Whatever is common to A and B. It will have to be implemented in the classes
}
public interface IACInterface
{
//Whatever is common to A and C. It will have to be implemented in the classes
}
public interface ICDInterface
{
//Whatever is common to C and D. It will have to be implemented in the classes
}
public class ABCDBase
{
//Whatever is common to all classes
}
public class A : ABCDBase, IABInterface, IACInterface
{
}
public class B : ABCDBase, IABInterface
{
}
public class C : ABCDBase, IACInterface, ICDInterface
{
}
public class D : ABCDBase, ICDInterface
{
}
You can create later in a static class extension methods for your interfaces to not duplicate the code for your methods in the Interfaces implementations (In other words, don't define methods in your interfaces, only properties). With refactoring can be really easy to implement the properties in your interfaces.
It would be nice to have extension properties. Hopefuly in the future.
EDIT
Like this:
public static class Helper
{
public static void IABMethod1(this IABInterface aOrBObject, arguments args)
{
//This will be available for any A or B object without duplicating any code
}
}

C# class design - what can I use instead of "static abstract"?

I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.

When would you use Abstract methods over virtual methods in C#? [duplicate]

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.

Categories

Resources