File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting result" Watch "Casting result" New topic

Casting result


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.

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;
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="" target="_blank" rel="nofollow"></a>

Joined: Jan 02, 2001
Posts: 8
Thanks very much,Suresh. It is much clear.
I agree. Here's the link:
subject: Casting result
It's not a secret anymore!