wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes object references 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 "object references" Watch "object references" New topic

object references

Donald Nunn
Ranch Hand

Joined: Nov 11, 2000
Posts: 200
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
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.

<b>Donald Nunn</b><br />Sun Certified Programmer for the Java 2 Platform
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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;
I agree. Here's the link: http://aspose.com/file-tools
subject: object references
It's not a secret anymore!