wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes inheritance and class casting question 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 "inheritance and class casting question" Watch "inheritance and class casting question" New topic
Author

inheritance and class casting question

francis joseph
Greenhorn

Joined: Jul 31, 2004
Posts: 13
I have a question regarding casting of classes in runtime/compiletime.


class AA {
String s1 = "AA.s1";
String s2 = "AA.s2";

public int show() {
System.out.println("calling method in AA");
return 5;
}
}

class BB extends AA {
String s1 = "BB.s1";

public int show() {
System.out.println("calling method in BB");
return 10;
}


public static void main(String args[]) {
BB x = new BB();
AA y = (AA) x;
System.out.println(y.s1 + " " + y.s2 + y.show());
}
}


It prints the following answer:

calling method in BB
AA.s1 AA.s210

---------------------------


Here casting of x is done during compile time and hence the members of class, AA will be called. But howabout the method, show()? It calls the method in AA and the variables in BB. Just confused on why variables from superclass and methods from subclass.

Any help on explaining the situation would be highly appreciated.

Thanks.
smitha verghese
Ranch Hand

Joined: Jun 21, 2003
Posts: 42
hi,
with regard to ur query, in overriding the variables is been access with respect to the reference of the object and not the content, whereas in case of method it looks at the content of the object to access the relevant object

hence here
BB x = new BB();
AA y = (AA) x;
System.out.println(y.s1 + " " + y.s2 + y.show());

1.
For variable accessing it looks for the reference type ie (AA y ) and not the content.
2.For method accessing it looks at the content of the object ie (AA) x

Hope this helps you
smitha
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
Hi Joe,

To implement polymorphism Java uses dynamic method lookup for non-static methods. This means that the method that is actually invoked is determined at runtime according to the type of the object. It will be the method furthest down the hierarchy (i.e. the most specific) that matches the signature. There is no concept of dynamic lookup for fields in Java.

Jules
francis joseph
Greenhorn

Joined: Jul 31, 2004
Posts: 13
Thanks to Smitha and Julian for the great help.

Joe
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: inheritance and class casting question
 
Similar Threads
Doubt in String class
please explain the output?
static methods and NULL
Operators and Precedence
Object Creation & destruction