Do you assign a subclass object to a Superclass instance type only for overriding? Or are we doing this for something else also?
Example: Sub is subtype of Super and
When someone writes code like this, he/she is trying to follow a basic OO design principle which says -
Program to an interface, not to a concrete implementation
I have explained this principle in one of my blog posts. Look in the Class Inheritance VS Interface Inheritance section.
To summarize the post, when you use a reference of a parent type to refer to an instance of a sub-type, you get a lot of flexibility. For example, if you ever need to change your sub-type implementation in the future, you will be able to do that easily, without changing much of your code.
Consider the following method -
public void DoSomeStuff(Super s) {
s.someMethod();
}
and a call to this method -
DoSomeStuff(new Sub());
now, if you ever need to change the logic inside someMethod, you can easily do it by declaring a new subtype of Super, say NewSubType, and changing the logic inside that implementation. In this way, you will never have to touch other existing code which utilizes that method. You will still be able to use your DoSomeStuff method in the following way -
DoSomeStuff(new NewSubType());
Had you declared the parameter of DoSomeStuff to be of Sub, you would then have to change its implementation too -
DoSomeStuff(NewSubType s) {
s.someMethod();
}
and it may also chain/bubble to several other places.
Yes, but "overriding" is not the term i would use. Often, the reason to have a class hierarchy is not to alter the behavior of the super class, but to implement it. More often than not, the super class will either be an interface, and not a class, or be an abstract class following the template method pattern, where some methods are kept abstract and multiple subclasses implement those, but the general behavior is already fixed.
More concretely though, if we assign a subclass to a superclass instance variable like in your example, we want to limit the impact on our code in the case we exchange the subclass (we only need to edit one single line!)
The characteristics of OO design that allows this (to handle object as instances of a common supertype) is called polymorphism.
One would assign a sub-type instance of to a supertype variable to handle all possible subtype classes in a uniform fashion, e.g. using methods declared (but possibly overriden) by the supertype class.
Related OO topics you might find interesting to read about: