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?
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
car is derived from it, and so is
So, if you create an object of
truck type, the object can obviously point to its base class
This crux of it is the is-a relationship. A car
The point the author is getting at is when you have a variable that's declared to be of type
Exception, the actual object assigned to that variable is not necessarily an instance of
Exception itself - it may also be any of the subclasses of
Exception subclasses consist of objects that extend Exception, ie NullPointerException, ClassNotFoundException, OutOfRangeException. Only subclasses of Exception will ever be an Exception object.
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects.
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.