Originally posted by manish ahuja:
now i can call only meth1() with the super class reference
No; you can call meth1() from a B reference. Since B extends A, it inherits all of A's methods. B can either use them as they are written in A, or override them so they do something different. Create the following and then run the Pgm class:
I would like to know whats the use of the above approach
Can some one show me practical use of this approach. having a sub classobject in a super class reference
The Collection classes are a good example of a practical reason for using this approach. Remembering that all classes are implicated subclasses of the Object class, the Collection classes store objects of type Objects. You can then cast the Ojbect as it comes out of the Collection object so that you have the "ability" to call that objects true methods:
Without this ability, we would need thousands of different ArrayList classes to hold every conceivable type of Object. And then what would we do for the special objects we create that the developers of the JDK did not know about?
Take a look at the Campfire story
How my Dog learned Polymorphism for some more info. And if that wets your appetite, pick up the book
Head First Java � it gives one of the best explanations of
polymorphism and casting I have ever read.