0

Here's an example:

abstract class baseClass
{
  void aMethod
  {
    //something here...
  }
}

class derivedClass : baseClass
{
  void aMethod
  {
    //something here...
  }
}

void main()
{
  baseClass Object_1 = new derivedClass();
}

Why is Object_1 declared as baseClass? Why do programmers do that? What type is Object_1? Is it baseClass or is it derivedClass? What would be the difference if my Object_1 was created like this:

derivedClass Object_1 = new derivedClass();

?

I'm learning C# and that's the environment that interests me the most in this case.

Martin Maat
  • 714
  • 4
  • 23
mnj
  • 2,539
  • 3
  • 29
  • 58
  • This gets used in a factory pattern a lot when you don't know what the derived type is at compile time. Also, sometimes another class needs to hold a reference to some type of base class but again it doesn't know exactly what it is at compile time and instead figures it out at runtime. – Jarrett Robertson Jul 08 '16 at 18:14
  • In order to access the object via its base class' interface. I could have a List which contains Ferraris, Fords, Hondas, etc, but if I want to start all the cars simultaneously, then I can use the base class of Car's start() method and iterate through the Cars calling that method, for example. That way, you can group together object that have common base class, but differing subclass. – ManoDestra Jul 08 '16 at 18:16
  • Look into SOLID principles, particularly the [Liskov-Substitution Principle](http://stackoverflow.com/a/584732/4416750). – Lews Therin Jul 08 '16 at 18:17
  • 3
    Possible duplicate of [What is polymorphism, what is it for, and how is it used?](http://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used) – Paul Swetz Jul 08 '16 at 18:17
  • If you try to understand the simple-factory pattern, it will help you understand : http://www.dotnet-tricks.com/Tutorial/designpatterns/FUcV280513-Factory-Method-Design-Pattern---C – granadaCoder Jul 08 '16 at 18:17
  • 1
    " Object_1 was initialized using baseClass" usually does not mean "Object_1 *declared* as instance of baseClass". Unless you mean something else please edit your post. – Alexei Levenkov Jul 08 '16 at 18:23
  • If your question is why don't they use: Derived x = new Derived(); consider using IAnimal animal = new Dog(); The developer knows the code after the declarion is targeting the IAnimal interface. (Now replace IAnimal for Carnivore) and replice Dog for e.g. Cat) where Carnivore implements IAnimal. and both dog and cat are carnivore's... now suddenly you need to understand that the code using the animal might use a lot more than just IAnimal and you no longer can replace Dog for Fish... because it's not a carnivore.. – Wouter Jul 08 '16 at 18:25

2 Answers2

1

Why Object_1 was initialized using baseClass class?

It wasn't. Take a look what type stands after new, it is the derived type. What you have here is the derived type instance that has been referenced using the base type as the reference type.

Why do programmers do that?

Having a typed reference means that you can use object's members. Depending on what actual type of the hierarchy is used, you have access to corresponding set of members.

Derived o = new Derived()
o.xxx  <- full access to instance members

Base o = new Derived()
o.xxx. <- access is limited to members that are defined in the Base class

object o = new Derived()
o.xxx. <- you can always see an instance as of 'object' type
          and have most limited interface

Note that each time the actual type of the instance is Derived but for some reason you decide to look at it through different "glasses".

What type is Object_1

The actual type is always the one that stands after the new operator.

What would be the difference if my Object_1 was created like this:

No difference for the instance itself but you'd have a different way of accessing its members. In languages like C# you can always safely cast an instance to its base type (or any type up the hierarchy) but note that you cannot always do the same down the hierarchy:

Derived1 d = new Derived1();
Base     b = (Base)d;

// d and b point to the very same instance but they differ on what properties you are allowed to access

Derived2 d2 = (Derived2)b;

// casting to a derived type would work only if the instance was of this actual type
// in a worst case such cast would then end with a run-time error
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • Thanks for a detailed answer. About your (1) example: when you defined Base o = new Derived(); you said that object o can only access members that were defined in the Base class. What if Derived class had some more members than Base class? We won't be able to access them. How to deal with that? ABout your (2) example: you create object d of class Derived. Then you create a reference b to that object, BUT I don't understand why you cast d object to Derived type - yet you wanted b do be of Base type, not Derived type. – mnj Jul 09 '16 at 09:36
  • First, to access more members you can always upcast, if possible. As for the example, corrected that, my mistake. – Wiktor Zychla Jul 09 '16 at 09:46
1

One practical example: you want to pass a collection of things to a method. The method should do something with each of the things.

Before the collection can be passed to the method, it has to be created. To create a collection of things you need a class that has an Add method. A List class would do.

To the receiving method the capability to add things to the collection is irrelevant. It just needs to be able to enumerate the things in the collection. So you pass IEnumerable, not List.

In general, assigning an instance to a base type variable eliminates noise and narrows the room for making assumptions. It says "at this point the subtype doesn't matter so this is not more complicated than it would be for the base type." That eases the mind.

Martin Maat
  • 714
  • 4
  • 23