• 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

k&b master exam :polymorphism doubt

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a que from k&b book. The answer is "An exception is thrown at runtime.
Can someone explain it to me pls? Thanks.

class X{void go(){System.out.print("x";}}
class Y extends X{void go(){System.out.print("y";}}
class Z extends X{void go(){System.out.print("z";}}
class Chrome2{
public static void main(String [] args)}
X z = new Z();
X y = new Y();
Z y2 = (Z)y;
z.go();
y.go();
y2.go();

}

}
 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

Nisha
-----------------------
Z y2 = (Z)y;
-----------------------
Exception will come here

the run time type of y is Y.
So there is no relation between class Y and class Z.


--------------------------------------------------------
class X{void go(){System.out.print("x";}}
class Y extends X{void go(){System.out.print("y";}}
class Z extends X{void go(){System.out.print("z";}}
-----------------------------------------------------

See the declarations carefully

Y IS-A X
Z IS-A X

There is no Z IS-A Y.


Thanks

Anil Kumar
 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Anil is right.

As there is no relationship existing between y and Z, you cannot cast Y to a Z.

regards,
Gitesh
[ May 22, 2007: Message edited by: Gitesh R ]
 
Nisha Pinjarkar
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Anil !
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic