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