Thanks. Now I understand that for example, a Dog can be treated as an Animal, or as a Pet. But I still wonder, why would I want to limit my methods only to Pet or Animal. First off, Dog has some of its own unique methods that neither Pet or Animal superclasses have have. Second, isn't it easier to make a Dog object, and only call on it Pet or Animal methods, instead of making an object with a reference of Pet or Animal? Can you please give me real life examples when using a superclass as a reference for an object is useful.
Joined: Dec 08, 2012
When you use a superclass reference to an object of a subclass, Java retains full knowledge of the class of which the object belongs. You can still access the unique methods by inserting an explicit cast like so:
This is assuming bark() is a method unique to the Dog class.
To see the benefits of why you would want the superclass reference, just google "benefits polymorphism Java" or something.
and your program will continue to work exactly as before without any other changes.
As far as class hierarchies are concerned, it also has some benefit, but usually when dealing with implementations. Continuing the above example, several of Java's List classes are actually subclasses of AbstractList, which saves the developers a lot of coding (and you, if you want to create your own); but the chances are you would use List rather than AbstractList when making references to them.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here