I am new the realm of Object Orientation and programming. There are some things I am still trying to understand.
For instance, I have the following code:
public abstract class ParentA
{
public virtual void MethodA()
{
Console.WriteLine("Doing somethin...");
}
}
public class DerivedClassA : ParentA
{
public override void MethodA()
{
Console.WriteLine("Doing something from derived...");
}
}
Now, I see some code where the class is instatiated like this:
ParentA p = new DerivedClassA();
p.MethodA();
Why not just instatiate the actually class you want to use and use it's members?
DerivedClassA d = new DerivedClassA();
d.MethodA();
I see this used a lot interfaces as well where is written like this:
public interface Animal
{
void Bark();
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("bark");
}
}
and then used in this manner:
Animal a = new Dog();
a.Bark();
Why not just do this??:
Dog d = new Dog();
d.Bark();
When does it matter?
Thanks for the help
:)
You're right; that does look odd, doesn't it?
The code:
Animal animal = new Dog();
is reasonably rare; normally if you knew you were making a Dog then you'd type the variable as Dog. What is more common is:
Animal animal = petStore.ObtainInexpensivePet();
where you don't know exactly what is going to come back; maybe a kitten, maybe an iguana, but you know it will at least be an Animal. It's the pet store that is creating the dog object, not you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With