Specify implement interface on derived class when base class implements it abtract - c#

I was wondering if there are any (runtime) difference if I implement an interface on a derived class if the base abstract class implements it already abstract:
public interface IFoo
{
void Bar();
}
public abstract class Base : IFoo
{
public abstract void Bar();
}
public class Derived : Base, IFoo // does this make any difference?
{
public override void Bar()
{
// do something
}
}
Is there any difference writing the "implemention" IFoo on Derived for example when I check if an instance implements an interface at runtime etc.?

Consider following on your example. Must the following be possible?
void f(Base b){
IFoo ifoo = b;
}
Because an object b is a Base, it must be an IFoo because Base implements IFoo. Now consider the following.
var d = new Derived();
f(d);
Since d is a Derived, it is a Base, because derived inherits from Base. Because of this, we can pass it to f, where it is then assigned to an IFoo, as we did before.
Essentially, because a derived class still is also all of its base classes, it already implements all of its base classes' interfaces. The designers of the language acknowledged this and there is no need to redeclare that a derived class is implementing interfaces that are implemented by its base classes.
I guess that maybe your question arises because of where you actually put the method body, but that really isn't relevant. The declaration of the interface is a contract for other consumers of objects of that type. Those consumers don't care where the method body was defined, all that they care is that when they have an IFoo, that it has a method with the signature void Bar() that can be called, as I showed earlier, inheritance must include all interfaces, so there is no need to declare them again.

The answer is No. There is no difference.
The Class Derived inherits from Base and Base in turn inherits from IFoo.
So, there is no necessity for you to "Implement" both Base and IFoo when defining the class Derived.
The hierarchy is established when you are defining the class Base:
public abstract class Base : IFoo
and continued when you define Derived as below:
public abstract class Derived : Base
The only problem may arise when you "Remove" Base from the hierarchy by redefining the Base class by removing the : IFoo implementation from the Base class definition as below:
public abstract class Base
The bottom line is: , IFoo is redundant and is therefore not necessary.

Related

Define protected abstract interface method as abstract in abstract class

I have an interface like this
interface IFoo
{
protected abstract int Compute();
int ComputeValue()
{
return Compute();
}
}
The idea being that Compute computes some value and ComputeValue maybe does some checks and then calls Compute to fetch the actual value. However, I now wonder how to implement this interface in an abstract class. I can do it like this
abstract class Bar : IFoo
{
public abstract int Compute();
}
but I dont want Compute to be called directly. However, when I try to implement it explicitly, e.g.
abstract class Bar : IFoo
{
abstract int IFoo.Compute();
}
I cannot define it as abstract in the abstract class Bar, which is what I want. Of course, I could do something like
abstract class Bar : IFoo
{
protected abstract int Compute();
int IFoo.Compute()
{
return Compute();
}
}
But I wonder is there a more elegant way of doing this without the additional extra method?
Not much you can do here. Though according toto the draft spec it was considered at some point to allow the support for explicit interface abstract overrides in classes (also see the reabstraction part):
Because we support explicit abstract overrides in interfaces, we could do so in classes as well
abstract class E : IA, IB, IC // ok
{
abstract void IA.M();
}
Open issue: should we support explicit interface abstract overrides in classes?
But it seems it was not followed through - see LDM-2019-03-27 Notes:
Explicit interface abstract overrides in classes
Allow abstract interface implementions in a class as well? Not an abstract class method implementing an interface method.
So either remove the Compute from the interface or use your current approach.

C# interface implementation with derived interface

In the following sample class "SomeClass" does not implement "ISomeInterface". Why can't I implement this by passing a more derived interface which does implement the base requirement. Whatever instance would be passed it would still implement the base, am I missing something?
namespace Test
{
public interface IBaseInterface
{
void DoBaseStuff();
}
public interface IChildInterface : IBaseInterface
{
void DoChildStuff();
}
public interface ISomeInterface
{
void DoSomething(IBaseInterface baseInterface);
}
public class SomeClass : ISomeInterface
{
public void DoSomething(IChildInterface baseInterface)
{
}
}
}
This restriction exists because the ISomeInterface expects that any IBaseInterface will satisfy the contract. That is, if you have the following:
public interface IBase {}
public interface IChildA : IBase {}
public interface IChildB : IBase {}
And an interface that expects IBase:
public interface IFoo { void Bar(IBase val); }
Then restricting this in a derived class as you would like:
public class Foo : IFoo { public void Bar(IChildA val) {} }
Would create the following problem:
IChildB something = new ChildB();
IFoo something = new Foo();
something.Bar(something); // This is an invalid call
As such, you're not implementing the contract you said you would.
In this situation, you have two simple options:
Adjust IFoo to be generic, and accept a T that is a derivation of IBase:
public interface IFoo<T> where T : IBase { void Bar(T val); }
public class Foo : IFoo<IChildA> { public void Bar(IChildA val) {} }
Of course, this means that Foo can no longer accept any IBase (including IChildB).
Adjust Foo to implement IFoo, with an additional utility method for void Bar(IChildA val):
public class Foo : IFoo
{
public void Bar(IBase val) {}
public void Bar(IChildA val) {}
}
This has an interesting side-effect: whenever you call ((IFoo)foo).Bar it will expect IBase, and when you call foo.Bar it will expect IChildA or IBase. This means it satisfies the contract, while also having your derived-interface-specific method. If you want to "hide" the Bar(IBase) method more, you could implement IFoo explicitly:
void IFoo.Bar(IBase val) { }
This creates even more inconsistent behavior in your code, as now ((IFoo)foo).Bar is completely different from foo.Bar, but I leave the decision up to you.
This means, with the second version in this section, that foo.Bar(new ChildB()); is now invalid, as IChildB is not an IChildA.
Why can't I implement this by passing a more derived interface which does implement the base requirement. Whatever instance would be passed it would still implement the base, am I missing something?
This is not allowed because of the reasoning I mentioned above, IFoo.Bar expects any IBase, whereas you want to further constrain the type to IChildA, which is not a super-interface of IBase, and even if it were it would not be allowed because it violates the interface implementation, though you could more easily define a second method at that point that does what you want.
Keep in mind that when you implement an interface, you subscribe to a contract, and C# will not let you violate that contract.
This violates the Liskov substitution principle.
ISomeInterface guarantees that the method can be called with any IBaseInterface instance. Your implementation cannot limit that to only accept IChildInterface interfaces.
From MSDN:
When a class or struct implements an interface, the class or struct must provide an implementation for all of the members that the interface defines
This method in the derived
void DoSomething(IChildInterface baseInterface)
Does not have the same signature as the one in the interface:
void DoSomething(IBaseInterface baseInterface)
IChildInterface and IBaseInterface are not the same types. Therefore your derived class does not implement all methods of the interface and you get the compilation error.
For a possible the logic behind having this as a restriction instead of the compiler understanding the inheritance see Liskov's substitution principle as in SLakes answer
You should change some interface to use some type which implements IBaseInterface,
then change the method signatures to use whichever child your SomeClass wants.
public interface ISomeInterface<TSomeChild> where TSomeChild : IBaseInterface
{
void DoSomething(TSomeChild baseInterface);
}
public class SomeClass : ISomeInterface<IChildInterface>
{
public void DoSomething(IChildInterface baseInterface)
{
}
}
If you could do that, then you could do this:
IAnimal cat = new Cat();
IAnimalTrainer dogTrainer = new DogTrainer();
dogTrainer.Train(cat);
An IAnimalTrainer can train any IAnimal. But a DogTrainer can only train Dogs. Thus it's illegal for DogTrainer to implement the IAnimalTrainer interface.

why abstract class can have a instance method?

We know if a class has an abstract method it will be abstract . It can't get an instance. But why can have an instance method? Does it have any meaning?
public abstract class AbsClass
{
public abstract void GetA();
public void Getb()
{ }
}
Not every method in an abstract class has to be abstract - when you derive from the class, the derived classes will inherit the non-abstract methods from the base class. It's extremely common to want to provide functionality in the base class that is common to all the derived classes (in fact, it's good programming practice to pull shared functionality up to the base class to avoid duplicating code in the various derived classes). It's also extremely common to want to provide "default" functionality in the base class that can then be overridden by individual derived classes.
The fact that you can't instantiate the base class itself doesn't matter - the non-abstract methods from the base class are called on instances of (non-abstract) derived classes.
Yes, it has a meaning.
It will be available for use in any derived class that does not explicitly implement it itself.
Example of a derived class:
public abstract class AbsClass
{
public abstract void GetA();
public void Getb()
{ }
}
public class DerivedClass : AbsClass
{
}
The following code will execute the abstract class's Getb() code:
var derivedClass = new DerivedClass();
derivedClass.Getb();
(Note that in the example above, the code wouldn't compile unless your derived class implemented GetA(), as it's declared as abstract, and therefore must be implemented in any concrete derived class)
Yes, it is perfectly well defined. It can't be invoked until you have an instance, which in turn indicates that you must have a concrete sub-type, but once you do the method is perfectly usable, for example:
AbsClass foo = new ConcreteClass();
foo.Getb();
Or indeed:
ConcreteClass foo = new ConcreteClass();
foo.Getb();
(since the sub-type inherits any types defined on base-types)
It is quite common for such methods to themselves use the abstract or virtual methods of the type - or indeed to be virtual.
The method will be the implementation for a concrete class that derives from AbsClass. Abstract means you can't create an instance of the class, not that it can't have any methods with implementation. You can also have instance data members in an abstract class.
As an example:
public class MyAbsClass : AbsClass
{
}
MyAbsClass mine = new MyAbsClass();
mine.Getb(); //This would call the implementation in AbsClass
If AbsClass were an interface, however, no implementation would be allowed.

Can an abstract class have only method signatures without implementation like interfaces?

Like Interfaces, can an abstract class have only method signatures without implementation? If yes:
How do abstract classes differ from interfaces?
How can another class, which has an abstract class as its base class, implement the body of the base class methods?
An abstract class can contain implementations, but it doesn't have to. This is one thing that makes it different from interfaces.
abstract class classA
{
abstract public void MethodA();
public void MethodB()
{
Console.WriteLine("This is MethodB inside ClassA");
}
}
class classB : classA
{
public override void MethodA()
{
Console.WriteLine("This is MethodA inside class B");
}
}
If you implement a method in the abstract base class and want to be able to override it later, you need to declare the method as virtual.
virtual protected void MethodC(){
//this can be overridden
}
in Java:
q1: The abstract class can contain method definitions AND normal methods while an interface cannot.
q2: from http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
//this is the abstract class
public abstract class GraphicObject {
abstract void draw();
}
//this is the implementation
class Rectangle extends GraphicObject {
void draw() {
...
}
}
Like Interfaces, can an abstract class have only method signature without implementation? If yes:
Yes, but can also have implementation ...
You can also have method implementation in the abstract class unlike interfaces, but you can not create an instance of an abstract class
Interfaces and Abstract Classes
Abstract Class versus Interface
Like Interfaces, can an abstract class have only method signature without implementation?
Yes. Abstract class can have method implementation.
How it differs from Interface?
Variables declared in an interface is by default final. An abstract class may contain non-final variables.
Members of a interface are public by default. An abstract class can have the usual flavors of class members like private, protected, etc..
Interface is absolutely abstract and cannot be instantiated; An abstract class also cannot be instantiated, but can be invoked if a main() exists.
In comparison with abstract classes, interfaces are slow as it requires extra indirection.
Refer the following links:
http://forums.asp.net/t/1240708.aspx/1
http://java.sys-con.com/node/36250
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Interface is a fully abstract class,
Means only signatures, no implementations, no data members.
On the other hand abstract class by defenition needs at least one abstract method.
Also it can have implementations.
And it also can contain data members which will be inherited to its inheritors.
The inheritor needs to implement the abstract method with the same signature in order to implement it
in JAVA Yes,
if you use abstract class this way, then there is no difference between interface and abstract class. what dose abstract class really matter is you can offer common implementation which expect to be inherited by sub class, that's interface is not able to do.
yes, as I said, that abstract class behave the same way as interface, you can just override the methods in sub class
For example:
public abstract class AbstractClassWithoutImplementation {
public abstract String methodA();
}
public class Implementation extends AbstractClassWithoutImplementation {
#Override
public String methodA() {
// TODO Auto-generated method stub
return "Yes";
}
public static void main(String[] args){
Implementation im = new Implementation();
System.out.println(im.methodA());
}
}
An abstract class is a class that cannot be instantiated. It is in between a concrete class (fully implemented) and an interface (not at all implemented).
It can contain regular members (variables, methods etc) that are fully implemented.
It can also contain abstract members that are not implemented. Any member that is not implemented, say a method signature, must be marked abstract.
So to answer your questions:
Like Interfaces, can an abstract class have only method signature without implementation?
Your wording is not clear enough to give a yes or no answer. An abstract class can have implemented methods, and it can have abstract methods that are not implemented which must be marked as abstract. It cannot have methods without implementation unless they are marked abstract.
If yes: How it differs from Interface?
Because it allows implementation of members.
How another class, for which this Abstract Class is acting as a base class, can implement the body of that method?
Simply needs to implement all the abstract members.
public abstract class A
{
public abstract void Test();
}
public class B : A
{
public void Test(){ return; }
}
Like Interfaces, can an abstract class have only method signature without implementation? If yes:
Yes, An abstract class can have all abstract methods even if it has a single abstract method it must be abstract.You can declare a class as abstract even if it doesn't have any abstract method.
How it differs from Interface?
In Interface ALL methods are abstract public bet in Abstract class it is not necessary that .Please read about Interface vs Abstract Class
How another class, for which this Abstract Class is acting as a base class, can implement the body of that method?
If your BaseClass is Abstract and ChildClass is extending Base class you can implement abstract method in ChildClass otherwise make ChildClass abstract also.
public class ChildClass extends BaseClass{
void display(){
/// Your Implementation here
}
}
abstract class BaseClass{
abstract void display();
}

Multiple inheritance with Abstract class and Interface

I have written the following code in C#.NET
public interface IWork
{
void func();
}
public abstract class WorkClass
{
public void func()
{
Console.WriteLine("Calling Abstract Class Function");
}
}
public class MyClass:WorkClass,IWork
{
}
On compiling, I didn't get any error. Compiler is not forcing me to implement the method "func();" in "MyClass", which has been derived from the interface "IWork".Latter, I can gracefully create a instance of the class "MyClass" and call the function "func()". Why the compiler is not forcing me to implement the "func()" method in the "MyClass"(which has been derived from "IWork" interface? Is it a flaw in C#?
While reading about this subject, I found I couldn't easily put it all together in my head, so I wrote the following piece of code, which acts as a cheat-sheet for how C# works. Hope it helps someone.
public interface IMyInterface
{
void FunctionA();
void FunctionB();
void FunctionC();
}
public abstract class MyAbstractClass : IMyInterface
{
public void FunctionA()
{
Console.WriteLine( "FunctionA() implemented in abstract class. Cannot be overridden in concrete class." );
}
public virtual void FunctionB()
{
Console.WriteLine( "FunctionB() implemented in abstract class. Can be overridden in concrete class." );
}
public abstract void FunctionC();
}
public class MyConcreteClass : MyAbstractClass, IMyInterface
{
public override void FunctionB()
{
base.FunctionB();
Console.WriteLine( "FunctionB() implemented in abstract class but optionally overridden in concrete class." );
}
public override void FunctionC()
{
Console.WriteLine( "FunctionC() must be implemented in concrete class because abstract class provides no implementation." );
}
}
class Program
{
static void Main( string[] args )
{
IMyInterface foo = new MyConcreteClass();
foo.FunctionA();
foo.FunctionB();
foo.FunctionC();
Console.ReadKey();
}
}
Gives the following output:
FunctionA() implemented in abstract class. Cannot be overridden in concrete class.
FunctionB() implemented in abstract class. Can be overridden in concrete class.
FunctionB() implemented in abstract class but optionally overridden in concrete class.
FunctionC() must be implemented in concrete class because abstract class provides no implementation.
To better understand the concept behind interfaces, I just give you the correct code of your implementation:
public interface IWork{
void func();
}
public abstract class WorkClass,IWork{
public void func(){
Console.WriteLine("Calling Abstract Class Function");
}
}
public class MyClass:WorkClass{
...
}
The basic rule: You need to include the interface always where the implementation is. So if you create a method within an abstract classes and define an interface of this method, you'll need to implement the interface into your abstract class and then all subclasses will automatically implement this interface.
As a matter of fact, interfaces have 2 kind of functions you can use them for:
1) As a "real" interface providing a generic handling of any class implementing the interface, so you can handle several kind of classes just by one interface (without knowing their real class names). While "handling" means: Calling a method.
2) As a help for other (framework) programmers not to mess up with your code. If you want to be sure that an method won't be replaced with another name, you define an interface for your class containing all "must have" method names. Even if the method is called nowhere, your programmer will get an compile error message when he changed the method name.
Now you can easily handle your Myclass just by the interface IWork.
Because the abstract class implements the interface.
If your class MyClass would not inherit from WorkClass you would get an error saying 'MyClass' does not implement interface member 'IWork.func()'.
But you also inherit from WorkClass, which actually implements the methods that the interface requires.
You can mark func() as abstract if you want to force the classes that inherits from it to implement it like this:
public abstract class WorkClass
{
public abstract void func();
}
I tried with the classes above in my solution.
It inherits the abstract class so the derived class have the func() method definition. This is the reason it was not able to show compiled errors.
func() is not marked as abstract in the WorkClass so you don't need to implement it in any classes that derive from WorkClass.
WorkClass implements the IWork interface so you don't need to implement it in MyClass because it inherits func() from WorkClass.
Since the func method in the abstract class is a non-virtual method, so the compiler thinks this method is a implementation of the interface.
When you extend MyClass to WorkClass, the method func() (which has been defined), is inherited.
So, when the interface IWork is implemented, the method 'func()' has already been defined. So, there are no more undefined methods in MyClass.
So, the class MyClass is a concrete class, due to which you are able to create a MyClass object without any compilation errors.

Categories

Resources