Reputation: 165
class Base
{
}
class Derive:Base
{
}
Base b=new Derive();
The above code works,but why we are able to create a Object of Derive Class and assigning it to Base Class reference. Also,the object variable 'b' will be able to access all non private variable and methods of Class Base,even though it is referencing Derive Class. What makes this possible,why the object variable 'b' which is referencing Derive Object is able to access the Base Class and not the Derive Class.
Upvotes: 2
Views: 100
Reputation: 19241
I think this is polymorhism question rather than inheritance.
One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Using polymorphism you can take advantage of this feature.
Polymorhism allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type.
Upvotes: 1
Reputation: 9890
The theory allowing the above code to work is called the substitution principle: When Derived
is a subtype of Base
, this forms a "is-a" relationship. The substitution principle postulates that wherever an instance of Base
is expected, it can be substituted by an instance of Derived
.
The reason you cannot access the properties and methods of the Derive
class later on is that (at least to a computer) there is no indication whatsoever that a variable of type Base
contains an instance of type Derive
which would allow access to these properties/methods. If you take another class DerivedToo : Base
which has other methods than Derive
you quickly see how the program could break if you assumed the Base
variable to hold a Derive
instance.
Upvotes: 3