Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Inheritance Doubt

 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<blockquote><font size="1" face="Verdana, Arial">code:</font><hr><pre name="code" class="core"><font size="2">class X
{
void print (X x){System.out.print("X");}
}

class Y extends X
{
void print (Y y){System.out.print("Y");}
}

class Z extends Y
{
void print (Z z){System.out.print("Z");}
}

class B{
public static void main(String[] args) {

X x2 = new Y();
x2.print(new Y());

X x3 = new Z();
x3.print(new Z());

}
}</font></pre><hr></blockquote>

The above code prints "XX". I expected it to print "YZ"
What i have understood from K&B is
> at compile time x2.print will chk if print method is present(and accessible) in class X. If not present it will give compile time error.
> At runtime polymorphism takes place and the method in class Y is invoked.
Can someone tell me if i have understood it right? If yes, then how does the above code print XX?
I faced the problem while solving Whizlabs6 .. code modified by me.
[ July 17, 2008: Message edited by: Milan Sutaria ]
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Milan,

The print method is over loaded,not over ridden.

Run time polymorphism takes places for over ridden methods. Overloaded methods are determined at compile time and are based on the reference type.

So x2.print(new Y()); or x3.print(new Z()); is executed, it calls the X print method.

Hope this clarifies.

Thanks,
Roopa
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, i missed on the point runtime polymorphism is for overridden methods.
Thanks for the reply.
 
You guys wanna see my fabulous new place? Or do you wanna look at this tiny ad?
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic