Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Fundamentals of Object Oriented Programming Level Two ยท Lesson 4 of 8

Module Three

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Module 3: Generics Fundamentals for Young Coders
โญ Module 3 ยท Level Two

Generics
Fundamentals

๐Ÿท๏ธ Write code once โ€” and make it work with any type

๐ŸŽฏ What you'll learn in this module

  • โœ” Why generics exist: type safety and reuse
  • โœ” How to write generic classes and generic methods
  • โœ” What type parameters and bounds mean
  • โœ” How to use generic collections in real code
  • โœ” Common pitfalls and the type erasure mystery
  • โœ” How to write reusable, type-safe utility code
โ“
Why Do Generics Exist?
The Big Idea

Imagine a box that can hold anything โ€” an apple, a book, or a cat. That's flexible, but messy: how do you know what's inside? You might pull out a cat when you expected an apple.

Generics let you label the box: Box<Apple> only accepts apples. Now the compiler checks it for you. You get flexibility and safety.

๐Ÿ“ฆ A labelled lunchbox: "sandwich only." If you try to put in a soda, it refuses โ€” before the mess happens.
๐Ÿงฑ
Generic Classes: One Blueprint, Many Types
Tool

A generic class uses a type parameter โ€” often written as T โ€” that you fill in when you create an instance. Instead of writing IntBox, StringBox, and DogBox, you write Box<T> once.

Box<Integer> and Box<String> are both valid โ€” and each is type-checked separately. One blueprint, many types.

๐Ÿฑ A bento box designed to hold one dish: fill it with rice, pasta, or salad โ€” same box, different fillings, labelled to keep them separate.
โš™๏ธ
Generic Methods: Type-Safe Helpers
Tool

A generic method declares its own type parameter, separate from the class. Example: public <T> T firstItem(List<T> items) returns the first item of any list โ€” with the type preserved.

Call it with firstItem(names), and the compiler infers T = String. You never have to cast. That's the magic of type inference.

๐Ÿฅ„ A universal spoon: it works with soup, cereal, or ice cream โ€” and you always get back the exact kind of food you scooped.
๐Ÿšง
Type Parameters & Bounds
Constraint

Sometimes T can be anything โ€” but sometimes you want to limit it. A bound says "T must be a Number" or "T must implement the Shape interface."

Example: <T extends Number> means T can be Integer, Double, or Long โ€” but not String. This lets you safely call number methods inside the class. Bounds are how you stay safe while keeping flexibility.

๐Ÿฆด A job posting for "veterinarian" implies you can treat animals โ€” not just anything alive. The bound restricts to what's actually needed.
๐Ÿ“š
Generic Collections in Practice
Everyday Use

You already use generics every time you write a typed collection:

List<String> โ€” a list of strings.
Map<String, Student> โ€” names mapped to students.
Set<Integer> โ€” a set of unique numbers.

Try to add a number to a List<String> โ€” the compiler refuses before your program even runs. That's the compiler being your bodyguard.

๐Ÿ“‹ A guest list labelled "family only" โ€” if you show up as a stranger, the bouncer (compiler) turns you away at the door.
๐Ÿ•ต๏ธ
Type Erasure & Common Pitfalls
Reality Check

Here's a surprise: in Java, generics are checked at compile time but erased at runtime. That means List<String> and List<Integer> look identical inside the running program. This is called type erasure.

Pitfalls to know: you can't create new T(), you can't do instanceof T, and you can't overload on List<String> vs List<Integer>. Generics are powerful โ€” but not infinite.

Works โœ… Fails โŒ
List<String> names = new ArrayList<>(); new T() โ€” no runtime type
void add(T item) obj instanceof T โ€” erased at runtime
<T extends Number> Primitive types like <int>
๐ŸŽญ The label says "apples only" โ€” but once it's off the shelf, the label disappears. You have to trust whoever packed it earlier.
๐Ÿงฐ
Writing Reusable, Type-Safe Utilities
Skill

Generics shine brightest in small utilities that many parts of your program reuse. Examples: max(List<T> items), filter(List<T>, Predicate<T>), or a Pair<A, B> class.

Notice the pattern: write the algorithm once, and it works for any type. Write it well and your whole codebase becomes shorter, safer, and easier to maintain.

๐Ÿ”ง A universal screwdriver with interchangeable bits: one tool, many jobs, no stripped screws.
โš ๏ธ Beginner trap: It's tempting to declare everything with <T> the moment you learn generics. But if you don't need the flexibility, plain types are clearer. Use generics when you genuinely need to work with many types โ€” not just because they look cool.

๐Ÿ› ๏ธ Hands-on activities (no boring stuff!)

1

The labelled box: Write a generic Box<T> class with put(T item) and get(). Use it with an Integer, a String, and a custom Toy class. Then try to mix types and watch the compiler complain.

2

First item helper: Write a generic method <T> T firstItem(List<T> items). Call it with List<String> and List<Integer>. Notice how the return type is inferred automatically.

3

Bound test: Write a method <T extends Number> double average(List<T> nums). Test with integers and doubles. Then try it with strings โ€” the compiler refuses. Explain why.

4

Typed map: Build a Map<String, Integer> that records the scores of three players. Retrieve a score, then try to insert a string as a score. Watch the type safety kick in.

5

Pair utility: Write a small Pair<A, B> class with first and second fields. Use it to hold (student name, grade) and (city name, population). One class, many uses.

6

Erased mystery (bonus): Create List<String> and List<Integer> variables. Try list.getClass() == otherList.getClass() โ€” and be surprised when they're "equal." That's type erasure in action.

๐Ÿ†

By the end of this module, you'll be able to: write generic classes and methods, use type bounds to constrain types, apply generic collections safely, explain type erasure, and build small type-safe utility classes your whole program can reuse.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’