aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting result" Watch "Casting result" New topic
Author

Casting result

Max
Greenhorn

Joined: Jan 02, 2001
Posts: 8
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

Joined: Nov 14, 2000
Posts: 104
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.


Suresh Selvaraj, (author of JQuiz)<br />SCJP2<br /><a href="http://www.decontconsulting.com" target="_blank" rel="nofollow">www.decontconsulting.com</a>
Max
Greenhorn

Joined: Jan 02, 2001
Posts: 8
Thanks very much,Suresh. It is much clear.
Max
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting result