473,413 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

question about polymorphism

Along with events and delegates, polymorphism has been something I sort
of struggle with every now and then. First, let me quote the book I'm
reading:

"Polymorphism is most useful when you have two or more derived classes
that use the same base class. It allows you to write generic code that
targets the base class rather than having to write specific code for
each object type."

And here is the example in the book:

public virtual string GetDisplayText(string sep) // located in
Product base class
{
return code + sep + price.ToString("c") + sep + description; //
code, price, and description are private fields (for properties); sep is
a seperator character, like tab or newline
}

public override string GetDisplayText(string sep) // in Book subclass
{
return base.GetDisplayText() + sep + author;
}

public override string GetDisplayText(string sep) // in Software subclass
{
return base.GetDisplayText() + sep + version;
}

First off, a quick question that just popped into my head: When
GetDisplayText is called from the two overridden methods, why doesn't it
have an argument?

Ok, the real question: If you are going to override a virtual method
with another method that is more specific to a particular subclass, like
the two overridden methods above, then how does this accomplish what the
above quote says? I see that the virtual method is generic for any
Product object, but if you have to override methods for the subclasses
in order to use polymorphism at all, then how exactly does this prevent
"having to write specific code for each object type"?

Thanks,
John
Nov 17 '05 #1
3 1587
John Salerno <jo******@NOSPAMgmail.com> wrote:
Along with events and delegates, polymorphism has been something I sort
of struggle with every now and then. First, let me quote the book I'm
reading:

"Polymorphism is most useful when you have two or more derived classes
that use the same base class. It allows you to write generic code that
targets the base class rather than having to write specific code for
each object type."

And here is the example in the book:

public virtual string GetDisplayText(string sep) // located in
Product base class
{
return code + sep + price.ToString("c") + sep + description; //
code, price, and description are private fields (for properties); sep is
a seperator character, like tab or newline
}

public override string GetDisplayText(string sep) // in Book subclass
{
return base.GetDisplayText() + sep + author;
}

public override string GetDisplayText(string sep) // in Software subclass
{
return base.GetDisplayText() + sep + version;
}

First off, a quick question that just popped into my head: When
GetDisplayText is called from the two overridden methods, why doesn't it
have an argument?
It should have - unless you've got another method with no parameters in
the base class, the above code won't compile.
Ok, the real question: If you are going to override a virtual method
with another method that is more specific to a particular subclass, like
the two overridden methods above, then how does this accomplish what the
above quote says? I see that the virtual method is generic for any
Product object, but if you have to override methods for the subclasses
in order to use polymorphism at all, then how exactly does this prevent
"having to write specific code for each object type"?


You don't have to write different code to *use* each different type.
Instead of writing:

string x;
if (foo is Software)
{
x = ((Software)foo).GetSoftwareDisplayText(...);
}
else if (foo is Book)
{
x = ((Book)foo).GetBookDisplayText(...);
}

you can just write:

string x = foo.GetDisplayText(...);

and the right version will be called.

Take another example - Streams. I usually don't care whether I'm
reading from a file, memory, or the network when I'm reading from a
Stream - I just want to read the data. Because they all inherit from
the same base class, I can treat them all the same way. Note that
interfaces provide this ability too - using a base class allows
inheritance of implementation as well as interface.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Jon Skeet [C# MVP] wrote:
You don't have to write different code to *use* each different type.
Instead of writing:


Ah, that makes it a lot clearer! Thanks!
Nov 17 '05 #3
1) The example is badly written and should pass the param to the base class version

2) The power of polymorphism is that you can write code that is based on using a base class reference and calls methods on it. However the actual code that runs is based on the type of the object that is hooked up to the reference. In your example

void PrintProduct(Product p)
{
Console.WriteLine(p.GetDisplayText(","));
}

This will print out different things if the actual object passed to the method is a Book or a Software object. So this is what is meant by writing generic code based on the base class rather than having to write the GetDisplayText method with special coding for Books and Software

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Along with events and delegates, polymorphism has been something I sort
of struggle with every now and then. First, let me quote the book I'm
reading:

"Polymorphism is most useful when you have two or more derived classes
that use the same base class. It allows you to write generic code that
targets the base class rather than having to write specific code for
each object type."

And here is the example in the book:

public virtual string GetDisplayText(string sep) // located in
Product base class
{
return code + sep + price.ToString("c") + sep + description; //
code, price, and description are private fields (for properties); sep is
a seperator character, like tab or newline
}

public override string GetDisplayText(string sep) // in Book subclass
{
return base.GetDisplayText() + sep + author;
}

public override string GetDisplayText(string sep) // in Software subclass
{
return base.GetDisplayText() + sep + version;
}

First off, a quick question that just popped into my head: When
GetDisplayText is called from the two overridden methods, why doesn't it
have an argument?

Ok, the real question: If you are going to override a virtual method
with another method that is more specific to a particular subclass, like
the two overridden methods above, then how does this accomplish what the
above quote says? I see that the virtual method is generic for any
Product object, but if you have to override methods for the subclasses
in order to use polymorphism at all, then how exactly does this prevent
"having to write specific code for each object type"?

Thanks,
John

[microsoft.public.dotnet.languages.csharp]
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Liza | last post by:
Hi guys, i'm trying to build a web service....... is there such thing as polymorphism in web services? i mean could i have two web services of the same name but different arguments such that i...
7
by: DJ.precario | last post by:
In a schematic way, I have a program with a virtual base class (MyClass), and some derived classes (MyClass1, Myclass2...) In main, I want to create a vector of objects of the classes that...
8
by: Locia | last post by:
What are the techniques used to implement parametric polymorphism in C++? A Polymorphic method can be virtual?
12
by: Meya-awe | last post by:
I am puzzled, what is the purpose of an interface? How does it work, what i mean is how does the compiler treats this? Why when we talk about separating user interface from business logic, an...
2
by: sarathy | last post by:
Hi all, I need a small clarification reg. Templates and Polymorphism. I believe templates is really a good feature, which can be used to implement generic functions and classes. But i doubt...
9
by: davetelling | last post by:
I am not a programmer, I'm an engineer trying to make an interface to a product I'm designing. I have used C# to make a form that interrogates the unit via the serial port and receives the data. I...
13
by: Jack | last post by:
I have a class called "Base". This class has a protected member variable "m_base" which can be retrieved using the public member function "GetBaseMember". "m_base" is initialized to "1" and is...
90
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
7
by: Markus Svilans | last post by:
Hello, My question involves virtual functions and inheritance. Suppose we have a class structure, that consists of "data" classes, and "processor" classes. The data classes are derived from...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.