This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "object references" Watch "object references" New topic
Author

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


<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;
Regards,
Manfred.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: object references