Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object references

 
Donald Nunn
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From Khalid's book p.216 ex. 6.24
public class Polymorphism {
public static void main(String args[]) {
A ref1 = new C();
B ref2 = (B) ref1; // 2
System.out.println(ref2.f());
}
}
class A { int f() { return 0; } }
class B extends A { int f() { return 1; } }
class C extends C { int f() { return 2; } }
I don't quite understand how the cast workd at label 2.
Thanks,
Donald
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Donald,
We have the following heirarchical tree:
A --> B --> C
In java we can always reference a subclass with a superclass reference. That is why we can perform the following with no compiler errors:
A ref1 = new C();
In the second line we can now can use the same logic with the B class (superclass of C):
B ref2 = (B)ref1;
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic