Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cast question..plz help...

 
Heinz Wu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. class A {
2. public int getVal() {
3. return 5;
4. }
5. }
6. class B extends A {
7. public int getVal() {
8. return 10;
9. }
10. }
11. public class test{
12. public static void main(String[] args) {
13.
14. B b = new B();
15. A a =(A) b;
16.int x= a.getVal();
17.System.out.println( x);

18.}
19.}
can anyone please tell me why the output is equal to 10?
I thought when b is casted by A (line 15), so is the output should be 5?
Thank You
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's polymorphism at its finest. When you cast B into A, you are just saying "I want to refer to this B object as if it is an A object". You can do that because B extends A. However, changing how you are referring to it (casting it to A) doesn't change what it really is - it is still really a B object. Because it is still really a B object, you are still executing the getValue() method defined in B.
 
Dean Jones
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm going to be naughty here and refer to pointing. Think of class A's properties "pointing" to class B's when you make that assignment. Class A will inherit anything that class B has but that matches class A's definition. If class B has some properties that class A doesn't, then class A will not inherit those properties. For instance:



The line with the comment "Not gonna happen" is going to cause a compiler error. However, the line above it would end up returning 2. Think of it this way, when you do:



You're making the object "a" inherit anything that B has that is similar. So, since "a" has a method named "getVal()", and B does too, "a" will inherit the method from B instead of using it's own. However, since "a" does't have a method "getAnotherVal()", then there is no way it can inherit that method.



Did I just make this more confusing than it was?
[ June 10, 2004: Message edited by: Dean Jones ]
 
Heinz Wu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I get it now...thanks guys!! Saving me so much time..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic