Java Generics in Java Generics in Java A Generic Solution

Why is it that you no longer need to cast milk/oranges when using Generics?

I don't fully comprehend how using generics allows the instances of box to use milk and oranges respective functions.

Daniel Onley
Daniel Onley
2,076 Points

Because of what happens when the Box class is called. When you add the "<>" in the Class declaration you're saying that you're passing in "Types" and not values: values can be anything while types are explicitly what you say they are.

Thus when declaring "Box<Milk>" the code states that this Box only has the Milk type.

Accordingly when declaring "boxOfMilk.add(oranges)" the IDE cross-checks the Box type that was declared above, which should be MIlk, and says this will create a compilation error. Why? Because "boxOfMilk" was made with the explicit Type "Milk" and only expects to receive the Milk type. Trying to use the add method to add "oranges" violates this explicitly, so the IDE can detect it, and warn us to fix it.

In other words...

Generics not only makes for cleaner & easier-to-read code, but Generics also let us set safeguards against our own mistakes when coding that an IDE can help detect. Even if you do not have an IDE to help you the process of using Generics makes these mistakes easier to spot since casting - and all of those parentheses - can be difficult to read and properly parse for a human.