Cast your reference types as little as possible. You need to be sure you can perform the cast (which you may need an instanceoftest), otherwise you may suffer an Exception. If the compiler thinks the cast is impossible, it will throw an error.
You should design your classes polymorphically so casting is unnecessary.
jaspreet manchinda wrote:what do casting actually do
It changes the way the language 'sees' an object, generally from a less specific to a more specfic type.
and when can we use object type casting
As Campbell said: as little as possible. With generics you can almost eliminate the need to do it at all.
The biggest remaining exception is in equals() methods:
Because the method takes an Object, it's usually necessary to cast it to the type being compared with, once you've established that it is, in fact, the one you want. So, for example:HIH
Isn't it funny how there's always time and money enough to do it WRONG?
Joined: Oct 13, 2005
Please search this forum; there is another thread about casting active today.
Joined: Feb 27, 2012
Campbell Ritchie wrote:Please search this forum; there is another thread about casting active today.