• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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 !
 
I knew I would regret that burrito. But this tiny ad has never caused regrets:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic