• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of casting

 
manish ahuja
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Rgrds
Manish
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, and if you want to see a test of Overriding a method, overide meth1() in B and run Pgm. Notice the diifference?
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you "get" something from an ArrayList, you get an Object back.

Object object = myList.get( args[0] );

Then you have to cast it to whatever it was that you put into the ArrayList.

String name = (String)myList.get( args[0] );
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic