jQuery in Action, 2nd edition*
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Ob Casting " Watch "Ob Casting " New topic
Author

Ob Casting

j.balaguru
Greenhorn

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 }
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

Joined: Jun 30, 2000
Posts: 1070
Take a look here, this might help some:
http://www.javaranch.com/ubb/Forum24/HTML/004812.html
Velmurugan
Greenhorn

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.
HTH
Velmurugan
Greenhorn

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: http://aspose.com/file-tools
 
subject: Ob Casting