Base class method access VS. abstract class Method access
-
Refering to the following two pair of classes:
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";public virtual void GetInfo() { Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); } } class Employee : Person { public string id = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine("Employee ID: {0}", id); } }
//---------------------------------------------------------
public abstract class animal
{
protected string ssn = "Poultry";
protected string name = "Mostly flying creatures";public abstract void GetInfo(); } class Seagull : animal { public string id = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); Console.WriteLine("Specimen ID: {0}", id); } }
Implementing them:
Public class A2Implementation {
public A2Implementation()
{
// This is base class access of the getinfo() method
Employee E = new Employee();
E.GetInfo();
// The following is abstract class access of the getinfo() method
// animal A = new animal(); // this would be wrong (instantiating it) instead, (if I were to use this) use a derive-keyword on this implementing class
Seagull A = new Seagull();
A.GetInfo(); // getinfo() is accessed through the Seagull class
}Question I get the exact same result in the implementation of the two pairs (unclear, albeit intentionally). Now what are the pros and cons of using an abstract definition here (the animal-Seagull track), or what is best; just using ordinary base class Access (the Person-Employee track)? Could I be mistaken in assuming that there is a concordance here.
Hi, 1) With an abstract class A you can define re-usable implementation for derived classes. This is a way of removing duplicate code in multiple derived classes. 2) With an abstract class you can defer implementation to derived classes e.g. defining abtract methods or properties. Why would you do that? Well you can call the abtract definition from implementation in the abstract class. 3) With an abstract class you can let implementation code be extended via overrides 4) With an abstract class you can declare collections of the abstract class, but add derived classes to the collection. I will try to make an example to illustrate above features:
abstract class A
{
// 2) A doesn't store the label content - a derived must
abstract string Label {get;};string ToLabel()
{
// 1) Implementation centralized - not in all derived classes
return this.Label;
}// 3) implementation that can be extended or even replaced
virtual void Writeline()
{
Console.Out.Writeline();
}
}class X : A
{
// 2) A says I must do this - I at least choose the content
override string Label{ get{ return "I am X!"; }}}
class Y : A
{
// 2) A says I must do this - I at least choose the content
override string Label{ get{ return "Me is Y!"; }}// 3) optionally extending implementation in abstract class
override void Writeline()
{
Console.Out.Writeline(">>>"); // extra before base
base.Writeline();
Console.Out.Writeline("<<<"); // extra after base
}
}void SomeCode()
{
// 4) Polymorphism - declaring a collection of abstract classes but adding instances of derived classes
List as = new List();
as.Add(new X());
as.Add(new Y());
foreach(A a in as) // 4 - accessing abstract implementation
{
Console.Out.Writeline(a.ToLabel); // 4 - no branching on implementation e.g. typeof(X) or typeof(Y)
}
}Lots of patterns make use of abstract classes e.g. http://en.wikipedia.org/wiki/Abstract_factory_pattern[^] and http://en.wikipedia.org/wiki/Composite_pattern[^]. Try play around with it and the different ways of calling up or down between abstract and con
-
Well yes. But what would be really cool is, if someone would be willing to take the time, to suggest a new code block, which could show where the abstract track is better. Anyone?
-
Thanks for that link. The article showed some variation there in the end, that brought in some ideas on how abstract classes could be useful (the IEnumerable). I think I will play With several code blocks and compare the use of them. I will read some books on the subject. I can also now can conclude on of my problems: - abstract classes without any implementations just look like Interfaces - It seems to me that using abstract classes in a small context is shear silliness, but in a larger "code-stretch" they are beneficial, as my second code post and it's answer shows. - A class that inherits from an abstract class cannot access the original implementation of a method
-
Hi, 1) With an abstract class A you can define re-usable implementation for derived classes. This is a way of removing duplicate code in multiple derived classes. 2) With an abstract class you can defer implementation to derived classes e.g. defining abtract methods or properties. Why would you do that? Well you can call the abtract definition from implementation in the abstract class. 3) With an abstract class you can let implementation code be extended via overrides 4) With an abstract class you can declare collections of the abstract class, but add derived classes to the collection. I will try to make an example to illustrate above features:
abstract class A
{
// 2) A doesn't store the label content - a derived must
abstract string Label {get;};string ToLabel()
{
// 1) Implementation centralized - not in all derived classes
return this.Label;
}// 3) implementation that can be extended or even replaced
virtual void Writeline()
{
Console.Out.Writeline();
}
}class X : A
{
// 2) A says I must do this - I at least choose the content
override string Label{ get{ return "I am X!"; }}}
class Y : A
{
// 2) A says I must do this - I at least choose the content
override string Label{ get{ return "Me is Y!"; }}// 3) optionally extending implementation in abstract class
override void Writeline()
{
Console.Out.Writeline(">>>"); // extra before base
base.Writeline();
Console.Out.Writeline("<<<"); // extra after base
}
}void SomeCode()
{
// 4) Polymorphism - declaring a collection of abstract classes but adding instances of derived classes
List as = new List();
as.Add(new X());
as.Add(new Y());
foreach(A a in as) // 4 - accessing abstract implementation
{
Console.Out.Writeline(a.ToLabel); // 4 - no branching on implementation e.g. typeof(X) or typeof(Y)
}
}Lots of patterns make use of abstract classes e.g. http://en.wikipedia.org/wiki/Abstract_factory_pattern[^] and http://en.wikipedia.org/wiki/Composite_pattern[^]. Try play around with it and the different ways of calling up or down between abstract and con
Thank you for the code, although it had to be modified a bit to run, but what do you mean by the following: - (derived class) always call base in overriden virtual method/property? This I do get, and I find it a good OO-realted advice: (abstract class) only declare fields as private. Thanks for the link that lead to this: [^] ... which talks about the usefulness of it all.
-
Thanks for that link. The article showed some variation there in the end, that brought in some ideas on how abstract classes could be useful (the IEnumerable). I think I will play With several code blocks and compare the use of them. I will read some books on the subject. I can also now can conclude on of my problems: - abstract classes without any implementations just look like Interfaces - It seems to me that using abstract classes in a small context is shear silliness, but in a larger "code-stretch" they are beneficial, as my second code post and it's answer shows. - A class that inherits from an abstract class cannot access the original implementation of a method
Quote:
A class that inherits from an abstract class cannot access the original implementation of a method
Actually it can, just call
base
.MethodName(...) to call the base implementation, even if you have overridden it. Works for overridden properties too. -
Thanks for that link. The article showed some variation there in the end, that brought in some ideas on how abstract classes could be useful (the IEnumerable). I think I will play With several code blocks and compare the use of them. I will read some books on the subject. I can also now can conclude on of my problems: - abstract classes without any implementations just look like Interfaces - It seems to me that using abstract classes in a small context is shear silliness, but in a larger "code-stretch" they are beneficial, as my second code post and it's answer shows. - A class that inherits from an abstract class cannot access the original implementation of a method
netfed wrote:
abstract classes without any implementations just look like Interfaces
More or less Yes, but their purpose are different. Interface is used to enforce a contract while Abstract class is used to build family trees.
netfed wrote:
A class that inherits from an abstract class cannot access the original implementation of a method
As the reply below already suggests, use base.MethodName() syntax.
-
Quote:
A class that inherits from an abstract class cannot access the original implementation of a method
Actually it can, just call
base
.MethodName(...) to call the base implementation, even if you have overridden it. Works for overridden properties too.public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}public abstract class E : D
{
public abstract override void DoWork(int i);
}public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}You can't call DoWork in class D from F. Which brought me to a new reason for using abstract classes: an abstract class can force derived classes to provide new method implementations for virtual methods.
-
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}public abstract class E : D
{
public abstract override void DoWork(int i);
}public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}You can't call DoWork in class D from F. Which brought me to a new reason for using abstract classes: an abstract class can force derived classes to provide new method implementations for virtual methods.
Yes, that's right, you can't call the base.base method since F overrides E not D. But I wouldn't agree that a base class can force its derived classes to provide a new method using virtual, since E has the choice to provide a new method or force it to the derived class. This is the function of the abstract operator, not the virtual one. The only reason that DoWork was forced to be overridden is because its base class (E) declared it as abstract, not because D declared it as virtual. In this instance E is the base class, not D, so it forces through the abstract keyword, not the virtual one.
-
Thank you for the code, although it had to be modified a bit to run, but what do you mean by the following: - (derived class) always call base in overriden virtual method/property? This I do get, and I find it a good OO-realted advice: (abstract class) only declare fields as private. Thanks for the link that lead to this: [^] ... which talks about the usefulness of it all.
Hi, You are welcome. Maybe you should post the runnable code, if you think it will help people. "but what do you mean by the following: - (derived class) always call base in overriden virtual method/property?" Inheritance in OOP is relatively loose. The only thing you can be certain about is that constructors are chained e.g. new Y() will call the constructor of Y that as its first statement will call the constructor of A, etc.... all the way up til the contructor of Object. You can then have your constructor code in different implementation called on the way back from Object. For all other methods/properties no such guarantee exists. In other words it is optional to call a base-method, which makes it pretty hard to manage private fields in the base class :) So these 2 go together: ----------------- - (abstract class) always expect virtual methods/properties to be called by derived classes - (derived class) always call base in overriden virtual method/property ----------------- It is just 2 calling convention rules that mimic the constructor chaining for all virtual methods. In this way we can design interdependency between A and X - even though the language supports that you can avoid calling base methods/properties. I hope it makes sense... otherwise I can elaborate. Thx for the nice link, btw. Kind Regards, Keld Ølykke
-
Hi, You are welcome. Maybe you should post the runnable code, if you think it will help people. "but what do you mean by the following: - (derived class) always call base in overriden virtual method/property?" Inheritance in OOP is relatively loose. The only thing you can be certain about is that constructors are chained e.g. new Y() will call the constructor of Y that as its first statement will call the constructor of A, etc.... all the way up til the contructor of Object. You can then have your constructor code in different implementation called on the way back from Object. For all other methods/properties no such guarantee exists. In other words it is optional to call a base-method, which makes it pretty hard to manage private fields in the base class :) So these 2 go together: ----------------- - (abstract class) always expect virtual methods/properties to be called by derived classes - (derived class) always call base in overriden virtual method/property ----------------- It is just 2 calling convention rules that mimic the constructor chaining for all virtual methods. In this way we can design interdependency between A and X - even though the language supports that you can avoid calling base methods/properties. I hope it makes sense... otherwise I can elaborate. Thx for the nice link, btw. Kind Regards, Keld Ølykke
Keld Ølykke wrote:
The only thing you can be certain about is that constructors are chained e.g. new Y() will call the constructor of Y that as its first statement will call the constructor of A, etc.... all the way up til the contructor of Object.
Maybe it's because I'm tired, but that reads to me like you're saying that instantiating an object will trigger the constructor all the way up the chain. If you are, this isn't the case. If you don't specify base on the constructor call, you stop at that point. What do you think gets printed out here:
public abstract MyBaseClass
{
public MyBaseClase() { Console.WriteLine("I'm in the base class constructor.");
}
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass() { Console.WriteLine("I'm in the derived class constructor");
}
....
MyDerivedClass myClass = new MyDerivedClass();