Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is your understanding of "Casting" ?

 
Fox Hu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the following code
class Super{
int a = 1;
int b = 2;
}
class Sub extends Super{
int a = 3;
int c = 4;
}
class Foo {
public static void main(String argv[]){
Sub sb = new Sub();
Super sp = (Super)sb;
System.out.println("sb.a = " + sb.a);
System.out.println("sp.a = " + sp.a);
}
}
The result is :
sb.a = 3
sp.a = 1
But I didn't create a new Super(), so where does sp.a = 1 come from ?
What happened when Super sp = (Super)sb;
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Data members can be hidden in subclasses, while methods can be overridden in subclasses. Deciding which method to call is determined at runtime, while de decision which data member must be read/altered, is decided at compile time by the compiler itself.
While you didn't explicitly constructed a Super object, it was created though, being a part of the Sub object, because a Sub object inherits from its parent class Super.
Your Sub object contains four data members, a and b from the Superclass and a and c defined in the Sub class itself. The first member 'a' is hidden by the latter member 'a'.
If you assign a Sub object to a Super variable, and later refer to member a, the compiler decides that you're refering to member a of the Super class. If you'd tried to refer to member 'c' using the Super variable, the compiler would have complained, because a Super object doesn't contain a member named 'c'. Just for the fun of it, change your classes like this:

kind regards
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words: Fields aren't polymorphic, only (instance) methods are.
Encapsulate the access to the fields in accessor methods, and you will see the difference.
 
Fox Hu
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means that the Methods will be overridded in the subclasses but Fields won't .
I know it now . Thank you .
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ths SG ,
Please change your name to be compliant with JavaRanch's naming policy.
Your displayed name should not be obviously fictitious. We really would prefer that you use your REAL name. Besides, I can't PRONOUNCE what you have there .
You can change your name: here.
Thanks,
Cindy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic