Originally posted by adam lui:
wat's the actual or practical benefit out of that declaration line in main() ?
can Parent ever do what Child can do?
The benefit isn't that a Parent can do what a Child can do - it's actually the other way around - a Child can do whatever a Parent can do. The benefit is that you don't have to
care what the Child is. It'll just do the appropriate thing.
Rather than pure inheritance, let's look at an example that uses Interfaces. The J2SE API contains an interface called "List". The classes LinkedList and ArrayList both implement that interface. You could certainly write this code:
That's fine and it'd work, but what happens if you decide that the performance of your application isn't very good? ArrayLists aren't particularly efficient when it comes to inserting new elements, but LinkedLists are great at it. You could change your code to be like this:
Yup, that'd work. It would also work much faster than the previous version. The problem is that anywhere you use that variable, you need to make a change in your code. I only had to make a change in the declaration and instantiation, but what if you were passing this object around? All of those lines would have to be modified, as well. It could turn into a nightmare.
Now, what if you had written the original line like this:
If you just use a List as your compile-time type,
polymorphism will take care of invoking the correct method and it makes maintenance much easier. Given the same need for change, you could do this:
How many places does your code need to change? Just one. Only where the actual object is instantiated.
Programming to an interface (or supertype) is a great way to reduce the amount of dependencies in your code. It helps keep your systems flexible and prevents maintenance nightmares.