• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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).]
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!