Learn Java Generics to make code more stable by detecting bugs at compile time

Developers prefer compile-time errors to run-time errors.

Why use Generics?

Method Overloading

Type Casting

// Output
100
Exception in thread "main" java.lang.ClassCastException: class java.lang.Double cannot be cast to class java.lang.Integer (java.lang.Double and java.lang.Integer are in module java.base of loader 'bootstrap')at com.learncsdesign.GenericType.main(GenericType.java:25)

Generic Types

Multiple Generic Types

Generic Methods

// Output
Hello World
Hello learncsdesign:200.02

Bounded Generic Types

Type Inference

Wildcards

Integer is a subtype of Number
ArrayList<E> is a subtype of List<E>
List<E> is a subtype of Collection<E>

Upper Bounded Wildcards

List<? extends T>

Lower Bounded Wildcards

List<? super T>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store