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

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.