-
December 3rd, 2009, 09:19 AM
#1
How to return an object of inherited class from abstract base class?
So for practice i'm designing a class library of Animals - cow, chicken, pig, duck. I made my base class "Animal" abstract and the functions within abstract as well. Other animals simply inherit class Animal.
Here's what i'm trying to accomplish and I'm not sure how:
I want to have the base class Animal to have a function called "GiveBirth()" which simply returns a new Animal, but of the type of animal it came from. Problem is, my class is abstract so i can't return an "animal", but i have to return a specific inherited animal.
Is there a way to use polymorphism so i can just return the correct animal?
This is a member function from my base class Animal:
Code:
public virtual Animal GiveBirth() // returns, if successful, 1 or more animals of same type.
{
Console.WriteLine("A new {0} has been born.", (this.GetType().ToString()).Substring((this.GetType().ToString().LastIndexOf('.')) + 1));
return new Animal(); // Won't work!
}
-
December 3rd, 2009, 09:29 AM
#2
Re: How to return an object of inherited class from abstract base class?
Use this instead:
Code:
public abstract Animal GiveBirth();
Each subclass will be forced to implement this method and then each subclass can return the correct type of animal. There's a fancier way around this using generics, but you may not want to use that for your assignment.
Code:
(this.GetType().ToString()).Substring((this.GetType().ToString().LastIndexOf('.')) + 1))
Could be better written as:
Code:
(this.GetType().Name)
www.monotorrent.com For all your .NET bittorrent needs
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
-
December 3rd, 2009, 09:40 AM
#3
Re: How to return an object of inherited class from abstract base class?
Thanks,
I was trying to avoid implementing it in each class... but Generics is the next chapter so I'll find a way then
Thanks for the MemberInfo.Name tip!
-
December 3rd, 2009, 02:52 PM
#4
Re: How to return an object of inherited class from abstract base class?
Originally Posted by PolishPaul
Thanks,
I was trying to avoid implementing it in each class...
Ahh, but that is how polymorphism works! Each derived class implements their own routine, it is the interface that is standard across the inheritance hierarchy.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|