Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic object reference and use question using c#

Tags:

c#

object

oop

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

:)

like image 944
NewGuy1667 Avatar asked Sep 08 '26 23:09

NewGuy1667


1 Answers

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.

like image 52
Eric Lippert Avatar answered Sep 10 '26 13:09

Eric Lippert