Originally posted by Nasir Khan:
Hi Friends,
Consider the code
_____________________________
class guitar{
private String play(){return "rock";}
public String go() { return play(); }
}
class ibanez extends guitar{
String play(){return "metal";}
}
class music {
public static void main(String s[]){
guitar g=new ibanez();
System.out.println(g.go());
}
}
__________________________________
Could anyone explain the outcome....
I know it got to do somthing with dynamic method lookup but
still the concept is not that clear to me.
please help!
Regards,<BR>Shree
Regards,<BR>Shree
Originally posted by shree vijay:
<code>
class guitar{
private String play(){return "rock";}
public String go() { return play(); }
}
class ibanez extends guitar{
String play(){return "metal";}
}
class music {
public static void main(String s[]){
guitar g=new ibanez();
System.out.println(g.go());
}
}
</code>
Hi, i think i can get a bit.
When the compiler compiles a program, it checks whether the method you call is accessible.
Consider the assignment
guitar g = new ibanez();
and then,
g.go()
when the compiler sees g.go() it checks the type of the variable g. The type of the variable g is guitar. And the go() method is of course available in the class guitar. So, it compiles fine.
But when the program is run, then what really matters is the type of the object you have assigned to the reference, not the type of the reference. Here the type of the object in memory for the reference g is ibanez. Now the question, is does ibanez class have the go method? Yes, it does, because it inherits it from the base guitar. So, the method call to the base class method is issued. Now, the go() method calls the play() method of guitar. (This is the case of the private play() called by the other member method go() which is perfectly legal)
Therefore, the output is 'Rock'
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>"Those who cast the votes decide nothing. Those who count the<BR>votes decide<BR>everything." <BR> -Joseph Stalin<HR></BLOCKQUOTE>
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>"Those who cast the votes decide nothing. Those who count the<BR>votes decide<BR>everything." <BR> -Joseph Stalin<HR></BLOCKQUOTE>
I've read about this kind of thing at the checkout counter. That's where I met this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|