Abstract class calling an abstract method - c#

Can anyone explain to me why this works the way it does. The output comes out to "Print This". But how does the base class call bar(), when there is no implementation.
abstract class Base
{
protected virtual void foo()
{
bar();
}
protected abstract void bar();
}
class Sub : Program
{
protected override void foo()
{
base.foo();
}
protected override void bar()
{
Console.WriteLine("Print This");
}
static void Main(string[] args)
{
Sub obj = new Sub();
obj.foo();
}
}

That's the whole point of an abstract class: that it will only ever exist concretely as an instance of the derived class(es). By declaring abstract methods or properties, it is simply forcing the derived class(es) to provide concrete implementations of those members. In this way, if you have an instance of type Base, you can call myInstance.bar and you know that the derived class has implemented it because it wouldn't compile otherwise.
By the way, use pascal case when naming methods, i.e. Foo and Bar.

But how does the base class call bar(), when there is no
implementation.
TL;DR answer: because of polymorphism.
If you got this question, how do you explain this?
public interface IStuffMaker
{
void MakeIt();
}
public class StuffMaker : IStuffMaker
{
public void MakeIt()
{
Console.WriteLine("yeah!");
}
}
IStuffMaker maker = new StuffMaker();
maker.MakeIt();
Why if maker is IStuffMaker can call MakeIt()? Because StuffMaker has implemented the so-called method.
In your particular case the reason behind being able to call your abstract method is because an abstract member is polymorphic and a derived class must override it to provide an implementation (same as interface members: they must be implemented).
Abstract classes are a mix of possible concrete members (with body) and abstract ones, which are just member signatures like interface members, but, in opposite to interfaces, since abstract classes can own concrete members, these can call abstract ones because they will be implemented in a derived class.

Related

Abstract method in public abstract class implementing an internal interface doesn't compile?

internal interface I_Foo
{
void Bar();
}
public abstract class A_Foo : I_Foo
{
public A_Foo() { }
abstract void I_Foo.Bar();
}
public class Foo : A_Foo
{
public Foo() : base() { }
internal override void Bar()
{
}
}
Hello! I'm trying to have some methods visible to outside code, and other only visible to my assembly. For this purpose, I made an internal interface I_Foo to serve as a contract to other parts of the assembly, a public abstract A_Foo to serve as abstraction for external code, and centralize some constructor functionality, and several different classes Foo that implement A_Foo and I_Foo explicitly to retain internal modifier.
However, in the A_Foo class, I get
'A_Foo.I_Foo.Bar()' must declare a body because it is not marked abstract, extern, or partial
even though the method is clearly marked as "abstract". If I add a body, I get "abstract is not a valid modifier".
I need this method to be explicitly declared, in order to be internal in a public class, and I need it to be abstract so I can override it in the actual implementation Foo.
Why doesn't the compiler let me?
Is there another way I can achieve the same thing?
Thank you.
Explicit interface implementations always have to have an actual implementation. The trick here is to making that just call a non-explicit (internal) abstract method:
public abstract class A_Foo : I_Foo
{
// Classes outside the assembly can't derive from A_Foo
// anyway, so let's make the constructor internal...
internal A_Foo() { }
void I_Foo.Bar()
{
Bar(); // Just delegate to the abstract method
}
internal abstract void Bar();
}
This still allows I_Foo to use internal types etc, because Bar is never exposed publicly - but it fits within the other rules of the language.
The method can not be abstract. THe problem is that you try to use explicit interface implementation (void I_Foo.Bar). Those methods can not be overwritten later - so they have to be implemented.
If you declare Bar directly (void Bar()) then it can be abstract.

Reimplementation of inherited interface methods

I did not fully understand using Interfaces, so I have to ask :-)
I use a BaseClass, which implements the IBaseClass interface.These interface only contains one declaration :
public interface IBaseClass
{
void Refresh ();
}
So I have implement a Refresh method in my Baseclass :
public void Refresh ()
{
Console.WriteLine("Refresh");
}
Now I want to use some classes which extends from these Baseclass and implements the IBaseClass interface :
public class ChildClass : BaseClass,IBaseClass
{
}
But cause of the implementation of "Refresh" into my BaseClass I does not have to implement the method again. What should I do, to force the implementation of "Refresh" into all childs of BaseClass as well as all childclasses of childclass.
Thanks kooki
You cannot force derived classes to re-implement the method in the way that you have specified. You have three options:
Do not define refresh in the base class. The interface will force child classes to implement it.
Eschew the interface if its only purpose was to force implementation and declare the base class as abstract as well as refresh, for which you would not give an implementation.
Define refresh in the base class as virtual. This allows overrides but will not force them. This is how ToString() works.
This is all assuming that your base class is larger than a single method. If indeed your code is exactly what you posted then Oded's answer is the best choice.
Simple. Don't supply a base class implementation, and you will have to implement the method in every inheriting class.
One way to achieve that is to make BaseClass abstract:
public abstract BaseClass : IBaseClass
{
public abstract void Refresh();
}
What should I do, to force the implementation of "Refresh" into all childs of BaseClass as well as all childclasses of childclass.
Like this:
interface IBase
{
void Refresh();
}
abstract class BaseClass : IBase
{
public abstract void Refresh();
}
class ChildClass : BaseClass
{
public override void Refresh()
{
// Your code
}
}
You can even omit the interface (my rule of thumb: if an interface gets implemented by exactly one class, dump the interface. Don't cling on to interfacitis. An abstract class quite much represents an interface, see also Interface vs Abstract Class (general OO)).
If you do need an implementation in the base class, build it as such:
(abstract) class BaseClass ( : IBase)
{
public virtual void Refresh()
{
// Your code
}
}
Which you can then call from your derived classes:
public override void Refresh()
{
// Your code
// optionally, to call the base implementation:
base.Refresh();
}
If you want to supply a default implementation, do it in your base class by marking it as virtual, so you can override that implementation in subclasses if you want.
Otherwise mark the method as abstract in your base class, so your subclasses are forced to implement the method themselves.
Lets take a look at this step-by-step.
1: You have an interface which defines your code contract defined like so:
public interface IBase
{
void Refresh();
}
2: You have a base class which implements your interface. (you will notice that the implementation for refresh is virtual. This allows you to override this method in derived classes).
class Base : IBase
{
public virtual void Refresh()
{
//Implementation
}
}
3: You have a super class which derives from Base. (you will notice that the derived class does not need to explicitly implement IBase as it's done at a lower level. I'll show you that you can test the integrity of this).
class Child : Base
{
public override void Refresh()
{
base.Refresh(); //You can call this here if you need to perform the super objects Refresh() before yor own.
//Add your implementation here.
}
}
At this point you might be thinking; "Ok, well then how is Child implementing IBase?". The answer is that it is implemented indirectly through Base, and because Child inherits Base, it also gets the implementation for IBase.
Therefore if you were to write:
IBase instance = new Child();
This is perfectly legal because essentially, Child derives from IBase indirectly.
If you wanted to test this, you can do this in your code:
bool canAssign = typeof(IBase).IsAssignableFrom(typeof(Child));
//canAssign should be true as Child can be assigned from IBase.
May be New Keyword can help u in that;
namespace ConsoleApplication1
{
interface IBase
{
void Referesh();
}
public class Base1 : IBase
{
public void Referesh()
{
Console.WriteLine("Hi");
}
}
public class Class1 : Base1, IBase
{
public new void Referesh()
{
Console.WriteLine("Bye");
}
}
class Program
{
static void Main(string[] args)
{
Class1 obj = new Class1();
obj.Referesh();
Console.ReadKey();
}
}
}

C# best partial interface implementation in base/abstract class

.net does not allow partial interface implementation in base classes. As a mitigation I've come to 3 alternate solutions. Please help me decide which is more universal in terms of refactoring, compile/run time errors, readability.
But first a couple of comments.
Of course you may always cast object to IFoo and call any method without any compiler warning. But it's not logical, you wouldn't do that normally. This construct wouldn't occur as a result of refactoring.
I want maximum separation. Direct class contract (public methods and properties) should be separated with interface implementations. I use interfaces a lot to separate object interations.
My comparison:
BaseClass1/MyClass1:
con: Have to create virtual abstract in BaseClass1 for each not implemented method of IFoo.
con: Additional method wrap - slight productivity impact at runtime.
BaseClass2/MyClass2:
con: no compiler warning if no implementation of Method2 in MyClass2. Runtime exception instead. Refactoring with poor unit test coverage may potentially destabilize code.
con: has to put additional obsolete construct to prevent direct method call from child classes.
con: Method2 is public for BaseClass1 so it's part of class contract now. Have to put "Obsolete" construct to prevent direct call, not via IFoo.
BaseClass3/MyClass3:
pro: (Compared to #2). More readable. You see that MyClass2.Method2 is IFoo implementation, not just some overriden method.
public interface IFoo
{
void Method1();
void Method2();
}
public abstract class BaseClass1 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
void IFoo.Method2()
{
IFooMethod2();
}
protected abstract void IFooMethod2();
}
public class MyClass1 : BaseClass1
{
[Obsolete("Prohibited direct call from child classes. only inteface implementation")]
protected override void IFooMethod2()
{
//some implementation
}
}
public abstract class BaseClass2 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
[Obsolete("Prohibited direct call from child classes. only inteface implementation")]
public virtual void Method2()
{
throw new NotSupportedException();
}
}
public abstract class MyClass2 : BaseClass2
{
public override void Method2()
{
//some implementation
}
}
public abstract class BaseClass3 : IFoo
{
void IFoo.Method1()
{
//some implementation
}
void IFoo.Method2()
{
throw new NotSupportedException();
}
}
public abstract class MyClass3 : BaseClass3, IFoo
{
void IFoo.Method2()
{
//some implementation
}
}
I like this version, the base class can't be instantiated because its abstract, the derived class must list IFoo in its declaration or else it won't be implementing the interface and then it is solely responsible for implementing the rest of the interface.
One drawback I can see is you can't explicitly implement the interface methods in the base class (ie no IFoo:Method1), but otherwise this is a fairly low overhead version.
public interface IFoo
{
void Method1();
void Method2();
}
public abstract class BaseClass1
{
public void Method1()
{
//some implementation
}
}
public class MyClass1 : BaseClass1, IFoo
{
public void Method2()
{
//some implementation
}
}
Ok, you could try the following as BaseClass is abstract:
public interface IFoo
{
void Method1();
void Method2();
}
public abstract class BaseClass : IFoo
{
public void Method1()
{
// Common stuff for all BaseClassX classes
}
// Abstract method: it ensures IFoo is fully implemented
// by all classes that inherit from BaseClass, but doesn't provide
// any implementation right here.
public abstract void Method2();
}
public class MyClass1 : BaseClass
{
public override void Method2()
{
// Specific stuff for MyClass1
Console.WriteLine("Class1");
}
}
public class MyClass2 : BaseClass
{
public override void Method2()
{
// Specific stuff for MyClass2
Console.WriteLine("Class2");
}
}
private static void Main(string[] args)
{
IFoo test1 = new MyClass1();
IFoo test2 = new MyClass2();
test1.Method2();
test2.Method2();
Console.ReadKey();
}
It is extremely bad to design a class that doesn't implement a well-defined contract. It is extreme because you firstly say that a class is capable of doing something. You explicitly highlight that the class can do stuff, but later in the code you say nahh, screw it, this class can live without implementation. Compiler very wisely asks you to implement the contract, but it is left up to you to decide.
Here are some common solutions
Bad solution
Throw an exception (NonImplementedException or NotSupportedException, see sample)
Declare it as obsolete (design it good from the beginning)
Better solution
Explicit interface implementation, but you still implement it (just kind of hide it)
Best solution
Use interface segregation (split your fat interface into thinner and more manageable ones)
I'd suggest having the abstract base class implement the interface with methods that call protected abstract methods, as shown in your first example, except for methods which some derived classes may not implement (following the "throw everything into IList but don't have all the methods actually work" pattern); those could be protected virtual stubs which throw NotSupportedException.
Note that it is up to the child class whether to expose any particular member of the interface as a like-named public member (which could call the appropriate abstract member).
The proper pattern in VB.net would be something like MustOverride Sub IFoo_Method1() Implements IFoo.Method1, which would avoid the extra function call overhead, but C# doesn't provide any means of implementing an interface with a protected member. Using explicit interface implementation for any method which may have to be overridden in a child class is somewhat icky, because it's impossible for the child's re-implementation of the interface to chain to the parent's implementation.

Object Oriented questiond about interface, abstract class and concrete class

1) OnCreate is public method of instantiated object from ClsLast class. But I wanted to restrict OnCreate method as protected.
interface InterFace {
void OnCreate();
}
class ClsFirst implements InterFace {
#Override
public void OnCreate() { }
}
class ClsLast extends ClsFirst{ }
class Test {
static void main(){
ClsLast objClsAct = new ClsLast();
objClsAct.OnCreate();
}
}
2) If I set OnCreate method as protected in InterFace
interface InterFace {
protected void OnCreate();
}
I'm getting error like this:
Illegal modifier for the interface method OnCreate; only public & abstract are permitted
3) If I set protected the method inside the ClsFirst class which implements InterFace like this:
interface InterFace {
void OnCreate();
}
class ClsFirst implements InterFace {
#Override
protected void OnCreate() { }
}
I'm getting this error:
Cannot reduce the visibility of the inherited method from InterFace
4) When I change the ClsFirst as abstract class and implements InterFace
interface InterFace {
void OnCreate();
}
abstract class ClsFirst implements InterFace {
}
I haven't to implement OnCreate method inside the ClsFirst class but ClsLast why?
Summary
How can I set Interface methods can only be used in derived classes?
Why can't I set methods with protected access inside Interface?
Why can't I set the accessor type of Class different than public after I implement the InterFace?
abstract classes that even if they implements an interface don't have to add unimplemented methods itself until one class derives abstracted classes. Why?
Thank you so much for your kind answers from now.
An interfaceis per definition a public contract. By implementing an interface you promise to provide a set of methods (and properties in other languages).
An interface has nothing in common with abstract classes because you can implement as many interfaces as you want on a single class and you implement instead of derive from it.
An abstract class is a base class, its like a partially functionally base which is used to share implementation details between different classes and provides a contract, too. However it's more an internal contract for all derived classes. Most times abstract classes are used to force all derived classes into a common pattern instead of sharing a public contract.
An abstract class can force a derived class to implement a method (or provide a suitable default implementation using the virtual keyword) and take use of this method (this is called Template Pattern).
If you implement an interface on an abstract class you don't have to provide all interface methods because the abstract class can not be instantiated. However if you don't implement all interface methods the first non abstract class in your hierarchy has to provide the missing methods.
Interface methods are always public. You can not reduce the scope of these methods. Use a protected abstract method instead in an abstract class.
You cannot do it. You can set methods both as virtual or abstract if you have an middle class which implements only a part of defined in interface contract.
You also cannot do it and the reason is simple, interface defines a contract, a set of operations which implementation is requested to have. You can implement the interface explicitly in your abstract class or restrict whole interface to be "internal", at least in c# in case if you would like to keep it 'in-house'.
You cannot do it because you promised to implement an interface.
Because another thing which you indirectly pointed once you mark class as an abstract is that you cannot instantiate it. Therefore you pass the requirement of implementing interface to the first class which you can create the instance of (I mean the chain of inheritance).
ad1. (c# example1)
interface IDummyInterface
{
void OnCreate();
void Process();
void OnFinish();
}
abstract class DummyAbstract : IDummyInterface
{
public virtual void OnCreate()
{
}
public abstract void Process();
public void OnFinish()
{
OnFinishInternal();
}
protected abstract void OnFinishInternal();
}
class DummyImplementor : DummyAbstract
{
public override void OnCreate()
{
// some other action here
base.OnCreate();
}
public override void Process()
{
}
protected override void OnFinishInternal()
{
}
}
Actually you can hide the method, until the your concrete class is casted to an "Interface" instance by implementing the Interface explicitly:
abstract class ClsFirst : Interface
{
void Interface.OnCreate()
{
this.OnCreate();
}
protected abstract void OnCreate();
}
ClsFirst last = new ClsLast();
last.OnCreate(); // Compiler Error, since OnCreate() is protected
Interface lastAsInterface = last;
lastAsInterface.OnCreate(); // Works, and calls the abstract OnCreate() method.
1) Why would you want to implement a protected interface to begin with? It does not add any value. You already have a way to make sure all derived classes comply with a given contract:
protected abstract void OnCreate();
2) Interfaces define a public contract. By public I mean that it has the same accesibility as the interface itselft. That is why accesibility modifiers are not permitted when defining interface members.
3) You can not decrease accesibility of any virtual member or interface members as you would be breaking the interface's contract. In your example ((IOnCreate)ClsFirst).OnCreate() would not be possible as OnCreate() is not accesible, which would mean that ClsFirst does not implement IOnCreate interface.

Why should an abstract class implement an abstract method of an abstract base class?

In the following example, the class Derived implements the abstract method method from class Main. But I can't think of a reason to fill in the method body in the abstract Derived class' implementation. Surely I should only implement abstract methods within real classes.
So how can I avoid doing it? What else can I do?
abstract class Main
{
public abstract void method();
}
abstract class Derived : Main
{
public override void method()
{
}
}
class RealClass : Derived
{
}
Usually if someone has specified that an abstract class has an abstract method, it's either because that class depends on that method for some of what it does, or it's because it's part of an expected API that it wouldn't make sense for the parent class to implement at this time. In either case, there must be an implementation once you get to a non-abstract implementation of the class.
Note also that if you are implementing an interface, you are required to state how that interface will be implemented, even if you just call the member abstract and pass the responsibility onto the subclass
public interface IPet {string GetNoise(); int CountLegs(); void Walk();}
public abstract class Pet : IPet
{
public string Name {get; set;}
public abstract string GetNoise(); // These must be here
public abstract int CountLegs();
public abstract void Walk();
}
When it comes to implementing the sub-class, you have a few choices depending on the circumstances. If your implementation is itself an abstract class, you shouldn't need to implement the abstract method.
public abstract class Quadruped : Pet
{
public override int CountLegs () { return 4; }
}
If your implementation is non-abstract, but the standard reason for the method in question really doesn't apply in your circumstance, you can do a no-op method (in the case of void methods), or return some dummy value, or even throw a NotImplementedException to indicate that the method should never have been called in the first place.
public class Fish : Pet
{
public override string GetNoise() {return "";} // dummy value: fish don't make noise
public override int CountLegs() {return 0;}
public override void Walk() {} // No-op
// public override void Walk() { throw new NotImplementedException("Fish can't walk"); }
}
Does that answer your question?
If there's no implementation of method in Derived then you can just make Derived abstract as well:
abstract class Derived : Main
{
}
class RealClass : Derived
{
public override void method() { ... }
}
EDIT: To clarify the comments - if there is no meaningful implementation of an abstract method in a subclass, then one does not need to be provided. This will however require that the derived class is itself abstract, and an implementation must be provided somewhere in the chain of descendant classes to some concrete subclass. I am not saying you should leave the implementation of method empty, as it is in the question, but rather you remove the override in Derived and mark the class abstract. This forces RealClass to provide an implementation (or itself be marked abstract).
All non-abstract descendant classes must provide concrete implementations of abstract methods. If you don't provide an implementation, then it's impossible to call that method.
If some concrete classes don't have an obvious proper implementation of a abstract method then your object design is incorrect. Maybe you should have an abstract class with some abstract methods (but not all). That class could have an both an abstract descendant and some concrete descendants.

Categories