473,399 Members | 3,919 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,399 software developers and data experts.

Beginner Inheritance Question

Hi all,

I have a question regarding inheritance. I'll use the following code
for an example (its been stripped down to the minimum):

// code start
using System;

class Animal
{
public string name;

public Animal(string pName)
{
name = pName;
}
}

class Dog : Animal
{
public string noise;

public Dog(string pName, string pNoise) : base(pName)
{
noise = pNoise;
}
}

class Cat : Animal
{
public Cat(string pName) : base(pName) { }
}

class MainApp
{
public static void Main()
{
Animal[] myPets = new Animal[3];

Cat animal1 = new Cat("Bob");
Cat animal2 = new Cat("Billy");
Dog animal3 = new Dog("Rover", "bark");

myPets[0] = animal1 as Animal;
myPets[1] = animal2 as Animal;
myPets[2] = animal3 as Animal;

for (int i = 0; i < 3; i++)
{
if (myPets[i] is Cat)
{
Console.WriteLine("Cat: {0}: ",myPets[i].name);
}
else if(myPets[i] is Dog)
{
Dog temp;
Console.WriteLine("Dog: {0}: ", myPets[i].name);

temp = (Dog)myPets[i];
Console.WriteLine(temp.noise);
}
}
}
}

// code finish

So I create an array of base class to store derived types in, but the
'Dog' type has an extra var which I want to access later.
The way I did it above was to recast a type to Dog (which has
previously been Dog but cast to Animal for storage in the array) from
Animal.

My question is, is there a better way to go about this? I'm guessing
(and learning) at the moment so don't know what good practice is.
Another possible solution is to have 'noise' in the base class, but
this makes the inheritence pointless.

Any help would be appreciated,

Chris

Dec 9 '05 #1
8 1434
Chris... I think that you are looking for polymorphism as a solution. In
the base
class define a _virtual_ method Voice() and override this method in Cat
and Dog.
Through the magic of polymorphism, the proper method will be called at
runtime, even if you store an array of references (variables) of type
Animal which
refer to instances of class Cat or instances of a class Dog.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 9 '05 #2

Jeff Louie wrote:
Chris... I think that you are looking for polymorphism as a solution. In
the base
class define a _virtual_ method Voice() and override this method in Cat
and Dog.
Through the magic of polymorphism, the proper method will be called at
runtime, even if you store an array of references (variables) of type
Animal which
refer to instances of class Cat or instances of a class Dog.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***


Hi Jeff,

I considered including such a method in Animal (base) - but I was
curious if there was a way to call a method of a derived class when it
was stored in an array of base class type.
Is it best to just declare every method used in derived classes in the
base class as virtual? I wasn't sure if this diminished inheritence in
any way (or bloat base class tremendously) - what I mean by this is
that a derived class might have new features, and to place those
features in an earlier class as a virtual type sort of removes the
reason for the inheritence doesn't it?
The example I posted above was an exercise in a book i'm working
through.

Dec 9 '05 #3
^MisterJingo^ wrote:

Hi Jeff,

I considered including such a method in Animal (base) - but I was
curious if there was a way to call a method of a derived class when it
was stored in an array of base class type.
Is it best to just declare every method used in derived classes in the
base class as virtual? I wasn't sure if this diminished inheritence in
any way (or bloat base class tremendously) - what I mean by this is
that a derived class might have new features, and to place those
features in an earlier class as a virtual type sort of removes the
reason for the inheritence doesn't it?
The example I posted above was an exercise in a book i'm working
through.


To clarify what I mean. I can understand if 2 derived classes share
functionality, and so that will be best placed as a virtual base class
method, but what if 1 of the derived classes contains unique methods,
which the other derived class doesn't. And you wish to store these
derived classes in an array and call the extra functionality (where
needed).
By storing in an array of base class, the new methods in one of the
derived classes will be inaccessible. Storing these methods as virtual
in base will solve this, but all the other classes (and those derived
from them) will contain methods which will never be used.
I hope this makes more sense.
So is there a way to call these functions (as the code in the first
post seems to do - but I think poorly) or should all possible methods
of future derivied types be blased as virtual in base?

Dec 9 '05 #4
"^MisterJingo^" <mi*********@gmail.com> a écrit dans le message de news:
11**********************@f14g2000cwb.googlegroups. com...

| To clarify what I mean. I can understand if 2 derived classes share
| functionality, and so that will be best placed as a virtual base class
| method, but what if 1 of the derived classes contains unique methods,
| which the other derived class doesn't. And you wish to store these
| derived classes in an array and call the extra functionality (where
| needed).
| By storing in an array of base class, the new methods in one of the
| derived classes will be inaccessible. Storing these methods as virtual
| in base will solve this, but all the other classes (and those derived
| from them) will contain methods which will never be used.
| I hope this makes more sense.
| So is there a way to call these functions (as the code in the first
| post seems to do - but I think poorly) or should all possible methods
| of future derivied types be blased as virtual in base?

You certainly would *not* include methods unique to some derived classes in
the base class. In fact, designing a class hierarchy from the top level down
is a very poor way to do things. You should always design your classes, in
the first palce, without any inheritance in mind; and then you will start to
see commonality which can logically be extracted out into a base class.

You should also investigate the use of interfaces and/or composition to
accomodate differences in "derived" classes.

Interfaces allow you to specify common behaviour that can cut across
inheritance hierarchies :

e.g.

interface IMakesNoise
{
void MakeNoise();
}

class Cat : Animal, IMakesNoise
{
...
}

class Car : Vehicle, IMakesNoise
{
...
}

This then allows you to have a list of IMakesNoise which have no common
inheritance and still treat them all the same.

But, whether you you straight-forward inheritance or composition to extend
classes, if you need to have differing methods in some subclasses, then
there is no other way than to test each object in a list whilst iterating
it.

However, you can simplfy your example by using polymorphism; i.e. marking
methods/properties as virtual/override :

e.g.

class Animal
{
private string name;
public Animal(string name)
{
this.name = name;
}

public virtual string Name
{
get { return name; }
set { name = value; }
}
}

class Dog : Animal
{
private string noise;

public Dog(string name, string noise) : base(name)
{
this.noise = noise;
}

public string Noise
{
get { return noise; }
set { noise = value; }
}
}

class Cat : Animal
{
public Cat(string name) : base(name) { }

public override string Name
{
get { return "Cat" + name; }
set { base.Name = value; }
}
}

Then your array code can change like this

Animal[] myPets = new Animal[3];

myPets[0] = new Cat("Bob");
myPets[1] = new Cat("Billy");
myPets[2] = new Dog("Rover", "bark");

for (int i = 0; i < 3; i++)
{
Console.WriteLine(myPets[i].Name);

if (myPets[i] is Dog)
Console.WriteLine(((Dog) myPets[i]).Noise);
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 9 '05 #5
Hi Joanna,

Thats exactly what I was looking for.

Thanks you.

Chris

Dec 9 '05 #6
FYI -- WROX publishes a "C# Class Design Handbook" which I'm finding
insightful.

<%= Clinton Gallagher

"^MisterJingo^" <mi*********@gmail.com> wrote in message
news:11********************@g14g2000cwa.googlegrou ps.com...
Hi Joanna,

Thats exactly what I was looking for.

Thanks you.

Chris

Dec 9 '05 #7
Thanks, i'll check it out. I'm currently working through the 'teach
yourself the c# language in 21 days' from sams, and 'windows forms
programming with c#'. If there any other books I should be looking
into, it would be great if anyone could suggest some (perhaps for
intermediate-advanced rather than beginner-intermediate).

Dec 9 '05 #8
MJ.... Inline
I considered including such a method in Animal (base) - but I was curious if there was a way to call a method of a derived class when it
was stored in an array of base class type.<

Sure. The key concept is that references (variables) have type and
objects
have class. So the reference of type base class still refers to an
object of class
Subclass. You can simply cast the reference to a valid type and invoke
the
visible methods in that type.

http://www.geocities.com/Jeff_Louie/OOP/oop6.htm
Is it best to just declare every method used in derived classes in the

base class as virtual? I wasn't sure if this diminished inheritence in
any way (or bloat base class tremendously) - what I mean by this is
that a derived class might have new features, and to place those
features in an earlier class as a virtual type sort of removes the
reason for the inheritence doesn't it?<

It is not wise to declare every method as virtual since this allows the
extender
of your class to make the base class method completely invisible. Unless
a
class is designed to be extended prefer private fields and non virtual
methods
and sealed classes. If you are designing a class to be extended then it
is wise
to look for instances where you can abstract behavior. Clearly you are
trying
to design a class that can be extended and Voice is a natural if not
classic
example of a polymorphic behavior. Voice is _not_ a good example of a
subclass specific behavior. A better example would be IRetriever which
would
involve responding to hand and whistle signals and retrieving. virtual
methods and polymorphic behavior is one of four common uses of
inheritance.

So let me be clear that an interface in C# represents an abstract IS_A
relationship similar to a pure virtual class in C++ and that C# supports
single
inheritance of implementation and multiple inheritance of interfaces.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 10 '05 #9

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

Similar topics

1
by: KK | last post by:
Windows Forms Inheritance, Incomplete? I was playing around with Windows Forms and found out this Forms Inheritance feature. The moment I saw that, I felt this can be used effectively if the...
44
by: lester | last post by:
a pre-beginner's question: what is the pros and cons of .net, compared to ++ I am wondering what can I get if I continue to learn C# after I have learned C --> C++ --> C# ?? I think there...
15
by: Pelle Beckman | last post by:
Hi all, I have a few newbie questions: In function declaration what does a 'const' mean inside the parameter list ? That it won't modify the value? void MemberFunction(const int x);
22
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete...
45
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using...
6
by: VR | last post by:
Hi, I read about Master Pages in ASP.Net 2.0 and after implementing some WinForms Visual Inheritance I tryed it with WebForms (let's say .aspx pages, my MasterPage does not have a form tag itself...
4
by: MikeB | last post by:
I've been all over the net with this question, I hope I've finally found a group where I can ask about Visual Basic 2005. I'm at uni and we're working with Visual Basic 2005. I have some books, ...
3
by: Marco Shaw | last post by:
Any good C# beginner blogs out there? Marco
11
by: bambam | last post by:
Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...

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.