I have read once in a book about exception where "an object of type Exception can be an instance of any subclassof Exception". I kinda get it, but there's still confusion can anyone clarify me the meaning of this?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
Author means to say that base class pointers can point to any object of derived classes.
A derived class will have the public/protected members of the base class. So, the casting is implicit and not harmful.
We have a class
So, if you create an object of
The point the author is getting at is when you have a variable that's declared to be of type
Exception subclasses consist of objects that extend Exception, ie NullPointerException, ClassNotFoundException, OutOfRangeException. Only subclasses of Exception will ever be an Exception object.
Boxer, Beagle, Collie = Subclasses of Dog
The point of polymorphism is that objects of a certain class can be treated in the same way as objects of their parent class, although their behavior may be different.
The prime example in Java is the Object class. All other classes in Java are subclasses of Object, and so can be used wherever Object can. A List is an ordered collection of Objects--thus (at least prior to Java 1.5) a List could hold 3 Foo objects, 14 Bar objects, and single Bat object. You don't necessarily know up front what the actual class of the objects in the List are, except that they are Objects.
Another good example in Java is the Number class. An Integer is an Number, so anywhere you can use a Number, you can use an Integer, or any of the other subclasses of Number (Long, Float, Double, Short, BigDecimal, AtomicInteger, etc). All of these subclasses of Number are a little different--Floats represent real numbers, whereas Integers represent integers--but all of them are Numbers and so can be described and accessed in terms of them being numbers.