Skip to content
Advertisement

How to avoid casting when accessing subclass variables from ArrayList of type superclass

JavaScript

I have a parent class Item, and a subclass HealingItem which extends that – for this method I want the player to be able to only access the HealingItem’s in the ArrayList of type Item.

Is there a more efficient method of performing this action which perhaps doesn’t involve continually casting for these types of issues, or is it even my design which may be faulty?

Thanks

Advertisement

Answer

Unfortunately, in Java you’re stuck with the “ceremony.” To fix your example per the discussion:

JavaScript

In Java 11 you can reduce some of the ceremony with “var”:

JavaScript

In Java 17 (preview feature as early as 14), you can use “enhanced” instanceof to combine the test with the cast:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement