In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface. I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something?
I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface.
I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface.
Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods
public abstract class Base
{
public void TemplateMethod()
{
AbstractMethod1();
AbstractMethod2();
}
public abstract void AbstractMethod1();
public abstract void AbstractMethod2();
}
public class Concrete : Base
{
public override void AbstractMethod1()
{
Console.Write("Override Abstract Method 1");
}
public override void AbstractMethod2()
{
Console.Write("Override Abstract Method 2");
}
}
public class Main
{
public Main()
{
var concrete = new Concrete();
concrete.TemplateMethod();
}
}
Related
I want to build a class that would have a property, in which there is an instance of a class, which implements an abstract class. Here's and example.
public class MyClass {
public MyDerivedClassA derived;
public void mainClassUtility () {
derived.foo();
}
}
public abstract class MyAbstractBaseClass {
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass {
public override void foo(){
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
return;
}
}
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use. There will be many implementations of the abstract class and depending on the current state of the program, MyClass might be using different implementations of the ABC. I want to write the program in a way, that no matter what implementation of the ABC is currently being used, there is a way to call it's methods by MyClass. What would be the best solution to this problem?
Unless I'm misunderstanding the question, you're pretty much there. Have MyClass expect a property of the abstract base class and you should be all set.
using System;
public class Program
{
public static void Main()
{
var myClassOne = new MyClass(new MyDerivedClassA());
var myClassTwo = new MyClass(new MyDerivedClassB());
myClassOne.mainClassUtility();
myClassTwo.mainClassUtility();
}
public class MyClass
{
public MyAbstractBaseClass Derived;
public MyClass(MyAbstractBaseClass derived)
{
Derived = derived;
}
public void mainClassUtility ()
{
Derived.foo();
}
}
public abstract class MyAbstractBaseClass
{
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassA");
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassB");
return;
}
}
}
How to require an implementation of an abstract class in C#?
You can not instantiate a abstract class - and thus can not use it for most cases. Except as variable/argument/generic type argument. You need to make a concrete (non-abstract) class that inherits from it. You can only use the abstract class as a variable/argument type. To guarantee that only stuff that inherits from it can be used there.
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use.
Then use the abstract class as type argument. It means only instaces of the abstract class (of wich there can be no instance) or instances of classes that inherit from it (that somebody else writes) can be used at that place.
Note that Abstract classes and Interfaces overlap in nearly all uses. There is a miriad small differences, but I do not think they mater. The only big difference I can see, is one of exclusivity:
a class can implement as many Interfaces as it wants.
You can only inherit from one abstract class. that means it is for a primary, exclusive purpose. That way you prevent some dumb ideas, like someone trying to make a Windows Form that is also a DBConnection.
In an Abstract class there are two abstract methods Method1() and Method2(),
but I like to inherit only one Method1() in derived Class, how to handle the situation?
public abstract class BaseClass
{
public abstract void Method1();
public abstract void Method2();
}
Really you can't... If you have to (and I would really question the reasons) some options are:
If you do not have any control over the abstract classes involved, and must use this specific abstract class, then, only way is to make the implementation in derived class throw a NotImplementedException.
public MyDerivedClass: BaseClass
{
public override void Method1()
{
// implementation of Method1
}
public override void Method2()
{ throw new NotImplementedException(); }
}
... or create another abstract base class called, say OnlyDOMethod1
public abstract class OnlyDoMethod1
{ public abstract void Method1(); }
then, modify Baseclass so it inherits from OnlyDoMethod1
public abstract class BaseClass: OnlyDoMethod1
{ public abstract void Method2(); }
and use OnlyDoMethod1 anywhere you only want Method1
public MyDerivedClass: OnlyDoMethod1
{
public override void Method1()
{
// implementation of Method1
}
}
It sounds like what you're looking for is interfaces. Something like this:
public interface ICanDoMethod1
{
void Method1();
}
public interface ICanDoMethod2
{
void Method2();
}
Then in your classes you can selectively implement them:
public class JustMethod1 : ICanDoMethod1
{
// implement Method1 here
}
public class Both : ICanDoMethod1, ICanDoMethod2
{
// implement both here
}
// etc.
Essentially, any given class either can or can not be polymorphically interpreted as any given type. If you want to be only part of a type, then what you really have is two types. C# is single-inheritance, so to implement multiple types you would use interfaces.
Conversely, you could also chain your inheritance. Something like this:
public abstract class Base1
{
public abstract void Method1();
}
public abstract class BaseBoth : Base1
{
public abstract void Method2();
}
public class JustOne : Base1
{
// only implement Method1 here
}
public class Both : BaseBoth
{
// implement both here
}
That'll work if the options stack, that is if you don't want to be able to pick and choose and either want "1" or "1 and 2" (but not just "2").
As a last resort, you can "selectively implement" methods by explicitly not implementing the others. It would looks something like:
public class JustOne : BaseClass
{
public override void Method1()
{
// implement
}
public override void Method2()
{
throw new NotImplementedException();
}
}
But this would be something of an anti-pattern, where your objects would advertise functionality that they intentionally do not support. This would mean that the type BaseClass should be considered very unstable/unreliable, because there's no way for anything consuming that type to know how it should actually behave.
Ultimately, it sounds like you've painted yourself into a corner with your types and you need to back up a little and re-think them. Liskov Substitution shouldn't be taken so lightly.
This is basic example of violation of one of SOLID principles Interface segregation principle
A client should never be forced to implement an interface that it
doesn’t use or clients shouldn’t be forced to depend on methods they
do not use
If you have abstraction where you need only some of method you need to split them in separated abstractions.
.NET do not support multi-inheritance from classes, nut have nice workaround for this problem -> interfaces.
If you care about your code, then you have only one option - split abstract class into two separated classes which have only one method.
If you work only with abstraction then interfaces is better approach, because you can implement multiply interfaces in one class.
public interface IMethodOne
{
void Method1();
}
public interface IMethodTwo
{
void Method2();
}
Then you can implement that both interfaces in the class which needs both methods. And use only one interface in the class with one method needs.
public abstract class BaseClass : IMethodOne, IMethodTwo
{
public abstract void Method1();
public abstract void Method2();
}
And class with one method
public abstract class BaseClassOneMethod : IMethodOne
{
public abstract void Method1();
}
I created two abstract classes and tried to create a class that inherits from both. But I get an error message.
abstract class AbstractClassOne
{
public abstract void ShowMessage();
public abstract void DisplayName();
}
abstract class AbstractClassTwo
{
public abstract void ShowMessage();
public abstract void DisplayPlace();
}
class DerivedClass : AbstractClassOne, AbstractClassTwo // here under AbstractClassTwo it shows the error "cannot have multiple base classes:"
{
}
So a class can only derive from one abstract class?
If can derive from more than one abstract class, then what happens if both classes define the same method, as is the case above (abstract class one and two both have a method showmessage(), so which one will be in the derived class)?
Multiple inheritance is not allowed by C# but it is allowed by C++.
To answer your question regarding the ShowMessage() method that is a known problem in c++ with multiple inheritance called "The Diamond Problem". see: http://en.wikipedia.org/wiki/Multiple_inheritance
So basically you will have to excitability state to which method you are refereeing when calling it e.g. ParentA::ShowMessage()
if you want to have a type that is polymorphic to 2 other types than you should create two separate interfaces and implement them. and if you want to reuse the same methods than you will have to use compositions.
Interfaces example:
public interface ISomeInterface
{
public void ShowMessage();
public void DisplayName();
}
public class ClassOne : ISomeInterface
{
public void ShowMessage()
{
//implementation
}
public void DisplayName()
{
//implementation
}
}
public class ClassTwo : ISomeInterface
{
public void ShowMessage()
{
//implementation
}
public void DisplayPlace()
{
//implementation
}
}
Interface with reusable Show Message Method using composition:
public class ClassTwo : ISomeInterface
{
private ISomeInterface _MyPrivateReusableComponent = new ClassOne();
public void ShowMessage()
{
_MyPrivateReusableComponent.ShowMessage()
}
public void DisplayPlace()
{
_MyPrivateReusableComponent.DisplayName()
//implementation
}
}
In C# it's not allowed to inherit from more than one class. To do what you want here, you need to use interfaces.
abstract class AbstractClassOne
{
public abstract void ShowMessage();
public abstract void DisplayName();
}
Interface IClassTwo
{
void ShowMessage();
void DisplayPlace();
}
class DerivedClass : AbstractClassOne, IClassTwo
{
}
You can't inherit from more than one class (abstract or otherwise), but in your case the abstract classes are pretty much interfaces, so you can turn them into interfaces and inherit from them (you can inherit from any number of interfaces).
No, abstract class whether having all abstract methods or only some, makes no difference as far as inheritance in concerned. you can inherit only one class (in C#) and as many interfaces as you want.
I have an interface so class writers are forced to implement certain methods. I also want to allow some default implemented methods, so I create a abstract class. The problem is that all classes inherit from the base class so I have some helper functions in there.
I tried to write : IClass in with the abstract base, but I got an error that the base didn't implement the interface. Well of course because I want this abstract and to have the users implement those methods. As a return object if I use base I can't call the interface class methods. If I use the interface I can't access base methods.
How do I make it so I can have these helper classes and force users to implement certain methods?
Make sure methods in the base class have the same name as the interface, and they are public. Also, make them virtual so that subclasses can override them without hiding them.
interface IInterface {
void Do();
void Go();
}
abstract class ClassBase : IInterface {
public virtual void Do() {
// Default behaviour
}
public abstract void Go(); // No default behaviour
}
class ConcreteClass : ClassBase {
public override void Do() {
// Specialised behaviour
}
public override void Go() {
// ...
}
}
Move the interface methods into the abstract class and declare them abstract as well. By this, deriving classes are forced to implement them. If you want default behaviour, use abstract classes, if you want to only have the signature fixed, use an interface. Both concepts don't mix.
Having faced with the same problem recently, I've came up with a somewhat more elegant (to my mind) solution. It looks like:
public interface IInterface
{
void CommonMethod();
void SpecificMethod();
}
public abstract class CommonImpl
{
public void CommonMethod() // note: it isn't even virtual here!
{
Console.WriteLine("CommonImpl.CommonMethod()");
}
}
public class Concrete : CommonImpl, IInterface
{
void SpecificMethod()
{
Console.WriteLine("Concrete.SpecificMethod()");
}
}
Now, according to C# spec (13.4.4. Interface mapping), in the process of mapping IInterface on Concrete class, compiler will look up for CommonMethod in CommonImpl too, and it doesn't even have to be virtual in the base class!
The other significant advantage, compared to Mau's solution, is that you don't have to list every interface member in the abstract base class.
I'm learning C# coming from C++ and have run into a wall.
I have an abstract class AbstractWidget, an interface IDoesCoolThings, and a class which derives from AbstractWidget called RealWidget:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget : IDoesCoolThings
{
void IDoesCoolThings.DoCool()
{
Console.Write("I did something cool.");
}
}
public class RealWidget : AbstractWidget
{
}
When I instantiate a RealWidget object and call DoCool() on it, the compiler gives me an error saying
'RealWidget' does not contain a
definition for 'DoCool'
I can cast RealWidget object to an IDoesCoolThings and then the call will work, but that seems unnecessary and I also lose polymorphism (AbstractWidget.DoCool() will always be called even if i define RealWidget.DoCool()).
I imagine the solution is simple, but I've tried a variety of things and for the life of me can't figure this one out.
You're running into the issue because you used explicit interface implementation (EII). When a member is explicitly implemented, it can't be accessed through a class instance -- only through an instance of the interface. In your example, that's why you can't call DoCool() unless you cast your instance to IDoesCoolThings.
The solution is to make DoCool() public and remove the explicit interface implementation:
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool() // DoCool() is part of the abstract class implementation.
{
Console.Write("I did something cool.");
}
}
// ...
var rw = new RealWidget();
rw.DoCool(); // Works!
In general, you use EII in two cases:
You have a class that must implement two interfaces, each of which contains a member that has an identical name/signature to another member in the other interface.
You want to force clients not to depend on the implementation details of your class, but rather on the interface that's being implemented by your class. (This is considered a good practice by some.)
The way you implement the interface is explicit implement void IDoesCoolThings.DoCool(), if you choose implicit implement interface.
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool()
{
Console.Write("I did something cool.");
}
}
Then it will work.
Read this :
C# Interfaces. Implicit implementation versus Explicit implementation
Change your declaration to:
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool()
{
Console.Write("I did something cool.");
}
}
You should do it this way:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget
{
public void DoCool()
{
Console.WriteLine("I did something cool.");
}
}
public class Widget : AbstractWidget, IDoesCoolThings
{
}
Usage:
var widget = new Widget();
widget.DoCool();