my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Ob Casting 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 "Ob Casting " Watch "Ob Casting " New topic

Ob Casting


Joined: Oct 13, 2000
Posts: 1
Pls explain;
1 class A{
2 int i =1;
3 int f(){return i;}
4 static char g(){return 'A';}
5 }
7 class B extends A{
8 int i=2;
9 int f(){return -i;}
10 static char g(){return 'B';}
11 }
13 public class OverrideTest{
14 public static void main(String arg[]){
15 B b=new B();
16 A a=(A)b;
17 System.out.println(a.i);//prints i of A. ie, 1
18 System.out.println(a.f());// prints -2
11 }
12 }
Any one, pls explain line 18, why it is still refer sub-class, even it is casted to its superclass, unlike field variable.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
Take a look here, this might help some:

Joined: Oct 11, 2000
Posts: 5
Non-static methods are resolved at compile-time.
So here, even if the reference variable 'a' is of super-class type 'A', it denotes to an object of type sub-class 'B'. At runtime, B's implementation of f() is called. Casting does not convert the object's type.

Joined: Oct 11, 2000
Posts: 5
Sorry for the mistake in the last post.
Non-static methods are resolved at runtime.
I agree. Here's the link:
subject: Ob Casting
It's not a secret anymore!