Can I have an instance of a class that inherits the values ​​of an instance of a superclass?

I use C #, but I think this is a pretty general OO question. Suppose I have a class called Animal, and it has properties like LegCount, EyeCount, HasFur, EatsMeat, etc.

Let's say I have an instance of a Animal. Suppose a has a LegCount of 4 and an EyeCount of 2.

Now I would like to create an instance d type Dog, which inherits from Animal. I would like to initialize d with all values ​​of a . I understand that I could create a constructor or some other method that Animal will take and spit out a new Dog with all the values ​​copied to, but I was hoping there was some kind of object-oriented principle / trick that engulfed me.

What I want to do in plain English:

Create a new instance of d for Dog, with all initial values ​​from a . The key is "all", as opposed to specifying each property individually.

When you create a class that inherits from some other class, you do not need to list all its inherited elements. He simply inherits them all. So I'm wondering if I can inherit values ​​in real instances.

+4
source share
4 answers

You cannot do what you ask for using some C # language construct, you need to manually write a mapping or delegation of code. Or look at AutoMapper for this.

+5
source

The function you want is called prototype inheritance or prototype-oriented programming . C # does not support this feature, so you are out of luck there.

You might want to use a language that supports prototype inheritance if your architecture fundamentally needs this feature. JavaScript is the most commonly used prototype inheritance language.

Inheriting prototypes can be quite complicated if you are not careful. If you are interested in this topic, see my article on some strange situations that you might encounter with prototype inheritance in JScript:

http://blogs.msdn.com/b/ericlippert/archive/2003/11/06/53352.aspx

+20
source

Can you try a different approach using the decorator template? An alternative to a subclass to extend functionality. Then all your values ​​are stored in an instance of the Animal class

http://www.dofactory.com/Patterns/PatternDecorator.aspx

+1
source
 public class Animal { public Animal(Animal otherAnimal) { if (otherAnimal == null) throw new ArgumentNullException("otherAnimal"); foreach (System.Reflection.PropertyInfo property in typeof(Animal).GetProperties()) { property.SetValue(this, property.GetValue(otherAnimal, null), null); } } } 

and then just call this Animal constructor from your Dog constructor (Animal otherAnimal)

But you still need to think about the design of your classes and make Animal an abstract class. Because you imagine an instance of the Animal class ..

+1
source

All Articles