Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting result

 
Max
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
some pelope have discuss if the following code could be run correctly. I compile and run it perfectly. The question is about the output. I thought it would be "44" and "Inside the child method",but the real thing is "34" , "Inside the child method".
Could anyone kindly explain this to me.
Thanks,
Max

public class abc{
int i= 34;
void check(){
System.out.println("Inside the parent method");
}
}
class def extends abc{
int i = 44;
void check(){
System.out.println("Inside the child method");
}
public static void main(String args[]){
abc a = new abc();
def d = new def();
a = d;
System.out.println(a.i);
a.check();
}
}
 
Suresh Selvaraj
Ranch Hand
Posts: 104
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Max,
The correct answer is "34" and "Inside the child method".
Here is the explanation...
"The 'variable' that gets displayed depends on the 'declared type of the object' and the 'method' that gets invoked depends on the 'actual type of the object and not on the declared type of the object'.
Since "a=d", the net result is " abc a = new def();"
Here 'a' is of type "abc" and 'd' is an object of type 'def'.
Hence a.i in "System.out.println(a.i);" would display "i=34" in class abc, and a.check() would invoke check() in class def.
Hope this clears your doubt.

 
Max
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much,Suresh. It is much clear.
Max
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic