From the course: Java 8+ Essential Training: Objects and APIs

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Cast objects as different types

Cast objects as different types - Java Tutorial

From the course: Java 8+ Essential Training: Objects and APIs

Start my 1-month free trial

Cast objects as different types

- When you're working with an inheritance hierarchy, you can treat objects as either their inherent types, or as their superclass types. A shirt is a clothing item, its superclass is a clothing item, and so it can be both. This is the nature of what's known as polymorphism in object-oriented programming. Polymorphism means something can be more than one thing at the same time. The object does everything the clothing item does, but it might do more that's unique to shirts. In this code, I'll go to the shirt class that I previously created, and I'm going to add a new instance variable, or field, it'll be a string, and its name will be Pattern. And I'll give it a default value of "Not Set". Next, I'll create a getter and a setter for this new field, and now this field is available to the rest of the application. I'll go back to the main class where I'm using that class. I already have some code that's creating an instance of the shirt class. And now I can use that object, Shirt, and I…

Contents