This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
Articles by Winston can be found here
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.