jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes cast question..plz help... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cast question..plz help..." Watch "cast question..plz help..." New topic

cast question..plz help...

Heinz Wu

Joined: May 04, 2004
Posts: 5
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) {
14. B b = new B();
15. A a =(A) b;
16.int x= a.getVal();
17.System.out.println( x);

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

Joined: Sep 13, 2002
Posts: 331
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.

Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"
Dean Jones

Joined: Jun 10, 2004
Posts: 6
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

Joined: May 04, 2004
Posts: 5
I think I get it now...thanks guys!! Saving me so much time..
I agree. Here's the link: http://aspose.com/file-tools
subject: cast question..plz help...
It's not a secret anymore!