• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ob Casting

 
j.balaguru
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pls explain;
1 class A{
2 int i =1;
3 int f(){return i;}
4 static char g(){return 'A';}
5 }
6
7 class B extends A{
8 int i=2;
9 int f(){return -i;}
10 static char g(){return 'B';}
11 }
12
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
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look here, this might help some:
http://www.javaranch.com/ubb/Forum24/HTML/004812.html
 
Velmurugan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
HTH
 
Velmurugan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for the mistake in the last post.
Non-static methods are resolved at runtime.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic