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.
posted 6 years ago
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.
because the interface usually specifies all public behaviour. If, later on, you decide that a linked list would be better, you can simply substitute:
List<String> list = new LinkedList<String>();
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.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here