• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

coverting sub class object to super class object

 
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Y is a subclass of class X. will this compile?

Class X objX = new Class X();
Class Y y= (Class Y) objX;

Ans: YES.

can anybody explain me why?

thanks!
Prabhu
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
please read about casting
what you are doing is down casting
the class x object to class y
 
tim bond
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Y is a subclass of class X. will this compile?

Class X objX = new Class X();
Class Y y= (Class Y) objX;

Ans: YES.

can anybody explain me why?


Class X objX = new Class X();
objx is an object of class x



class x is the superclass of class y



Class Y y= (Class Y) objX;

here you are creating a reference y (not an object)
and objx is being assigned to this reference y.
and the objx is being downcasted using (Class y).

thats why it is getting compiled.
 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This will not give any compile time error as you are explicitly type casting it.
So, the compiler will assume that whatever you are doing in explicit type casting is know to & you are responsible for that.so it will over look the error. But in run time it will give error.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic