This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi All I would like to know what is the use of casting Say if we have Class A with 1 method public void meth1() now i create a child class Class B extends A & add 1 more method public void meth2()
now in a main method i create A x = new B(); now i can call only meth1() with the super class reference 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
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.