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.
-
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.
Not sure what you try to achieve, but from the example you made it's clear that the base-class approach is better for you. When using abstract class you was unable to put
Name
andSSN
into the abstract (no room for this), but if these properties are common to all then it's much better to put it in some base (that's why it called base!)... -
Not sure what you try to achieve, but from the example you made it's clear that the base-class approach is better for you. When using abstract class you was unable to put
Name
andSSN
into the abstract (no room for this), but if these properties are common to all then it's much better to put it in some base (that's why it called base!)...Alright. I've managed to cram it in there, the abstract Properties, and I've changed the Whole lot to look a lot more similar With regards to content. Now here is what I got:
// -------- Ordinary class
public class animal1
{
protected string name1 = "Poultry";
protected string ssn1 = "Mostly flying creatures";public virtual void GetInfo() { Console.WriteLine("Name1: {0}", name1); Console.WriteLine("SSN1: {0}", ssn1); }
}
class Seagull1 : animal1
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Specimen ID: {0}", id);
}
}// -------abstract class
public abstract class animal2
{
public abstract string name2 { get; }
public abstract string ssn2 { get; }
public abstract void GetInfo();
}
class Seagull2 : animal2
{
public string id = "ABC567EFG";
public override string ssn2
{
get { return "Mostly flying creatures"; }
}
public override string name2
{
get { return "Poultry"; }
}public override void GetInfo() { // Calling the base class GetInfo method: Console.WriteLine("Name2: {0}", name2); Console.WriteLine("SSN2: {0}", ssn2); Console.WriteLine("Specimen ID: {0}", id); }
}
The implementation and output follows:
public class implementation
{
// the constructor
public implementation()
{
// This is base class access of the getinfo() method
Seagull1 E = new Seagull1();
E.GetInfo();// The following is abstract class access of the getinfo() method
Seagull2 A = new Seagull2();
A.GetInfo();
}
}Resulting text output:
Quote:
Name1: Poultry SSN1: Mostly flying creatures Specimen ID: ABC567EFG Name2: Poultry SSN2: Mostly flying creatures Specimen ID: ABC567EFG
It seems to me that the use of abstract classes in this case is redundant, and the first track is sufficient, let alone more efficient. I am wondering then when the abstract classes kicks in with their possible advantages? Could it be, if I introduced the Penguin which is not able to fly, that the flyingability becomes an issue urging the use of abstract classes?
-
Alright. I've managed to cram it in there, the abstract Properties, and I've changed the Whole lot to look a lot more similar With regards to content. Now here is what I got:
// -------- Ordinary class
public class animal1
{
protected string name1 = "Poultry";
protected string ssn1 = "Mostly flying creatures";public virtual void GetInfo() { Console.WriteLine("Name1: {0}", name1); Console.WriteLine("SSN1: {0}", ssn1); }
}
class Seagull1 : animal1
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Specimen ID: {0}", id);
}
}// -------abstract class
public abstract class animal2
{
public abstract string name2 { get; }
public abstract string ssn2 { get; }
public abstract void GetInfo();
}
class Seagull2 : animal2
{
public string id = "ABC567EFG";
public override string ssn2
{
get { return "Mostly flying creatures"; }
}
public override string name2
{
get { return "Poultry"; }
}public override void GetInfo() { // Calling the base class GetInfo method: Console.WriteLine("Name2: {0}", name2); Console.WriteLine("SSN2: {0}", ssn2); Console.WriteLine("Specimen ID: {0}", id); }
}
The implementation and output follows:
public class implementation
{
// the constructor
public implementation()
{
// This is base class access of the getinfo() method
Seagull1 E = new Seagull1();
E.GetInfo();// The following is abstract class access of the getinfo() method
Seagull2 A = new Seagull2();
A.GetInfo();
}
}Resulting text output:
Quote:
Name1: Poultry SSN1: Mostly flying creatures Specimen ID: ABC567EFG Name2: Poultry SSN2: Mostly flying creatures Specimen ID: ABC567EFG
It seems to me that the use of abstract classes in this case is redundant, and the first track is sufficient, let alone more efficient. I am wondering then when the abstract classes kicks in with their possible advantages? Could it be, if I introduced the Penguin which is not able to fly, that the flyingability becomes an issue urging the use of abstract classes?
It get me back exactly to the same point...
netfed wrote:
public virtual void GetInfo()
{
Console.WriteLine("Name1: {0}", name1);
Console.WriteLine("SSN1: {0}", ssn1);
}This code is common to all classes based on
animal1
, you never write it again. In the abstract version you have an emptyGetInfo
method (it's abstract so it must be empty!), and in every instance inherits this abstract class you must implementName
andSSN
... You see base classes used when you have a certain amount of common functionality that known. Abstract class are more like interfaces as they declare the structure of the class inherits them, with the addition of some common functionality... Again - based on your sample base class is better for you... -
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.
Abstract class provides you with an option to declare a non-instantiable base class from which your concrete classes inherit. You cannot instantiate an abstract class, you must instantiate one of your concrete classes. But if you wish to be able to instantiate the base class, then do not declare it abstract. If there is shared logic that can be generalized, use an abstract base class. If the base set of functionality is complete on its own, then you can use a concrete base class.
-
Abstract class provides you with an option to declare a non-instantiable base class from which your concrete classes inherit. You cannot instantiate an abstract class, you must instantiate one of your concrete classes. But if you wish to be able to instantiate the base class, then do not declare it abstract. If there is shared logic that can be generalized, use an abstract base class. If the base set of functionality is complete on its own, then you can use a concrete base class.
-
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?
-
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();