O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Casting with Reference Types

This is very similar to casting with primitives. But it's different. And there are some rules, young lady. Deviation will not be tolerated.

Simple Casting

A reference of any object can be cast to a reference of type java.lang.Object.

You can cast up the class hierarchy, and down the class hierarchy. But you can't cast laterally. This means that a reference to any object O can be cast to a class reference that is a subclass of O if, when it was created, O was a subclass of that class.

You can cast up the class hierarchy automatically—that is without using the cast operator.

Object o = "some string";

Object is up the hierarchy because String extends Object. String is down the class hierarchy from Object. If you cast ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required