• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance and class casting question

 
francis joseph
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to Smitha and Julian for the great help.

Joe
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic