Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is it possible to cast base to derived class ?  RSS feed

 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi,
Is it possible to cast a base class reference to derived without causing a class cast exception ?
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sahir,
Yes, but the base class should refer object of subclass to avoid the ClassCastException. Take a look at follwoing example --
CODE
------
<pre>

class Base
{
//...
}
class Derived extends Base
{
//...
}
public class Test
{
public static void main(String a[])
{
Base b; // Base class reference.
Derived d = new Derived(); // Object of derived class
// Now d holds the object reference of derived class.
// asign that to the Base class reference.
b = d; // valid no cast required, 'is a' conversion.
// Now cast the base class reference to the derived.
d = (Derived)b; // with cast.
}
}

</pre>
Hope this helps.
Regards
---------
vadiraj
------------------
*************************
There's a lot of I in J.
*************************
[This message has been edited by vadiraj vd (edited December 22, 2000).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!