Java generics are essential for writing type-safe, reusable code. They enable the creation of classes, methods, and interfaces that can handle various data types, enhancing code robustness and flexibility. This article illustrates generics using a shopping cart example that stores different fruit types, represented by custom classes.
Why Generics? The Limitations of Arrays
Java arrays are type-specific; an array of one type can't hold elements of another:
String[] fruits = new String[3]; fruits[0] = "Apple"; // Correct fruits[1] = 123; // Compile-time error
This type safety is beneficial, but arrays lack flexibility. Creating a shopping cart for various fruits (bananas, apples, grapes) using arrays would require cumbersome manual type handling.
Generics offer a solution: flexible yet type-safe data structures. Let's build this, starting with custom Fruit classes.
Step 1: Defining Fruit Classes
We'll define a base Fruit
class and subclasses for Banana, Apple, and Grape, each with unique properties.
// Base class for fruits public abstract class Fruit { private String name; public Fruit(String name) { this.name = name; } public String getName() { return name; } } // Specific fruit classes public class Banana extends Fruit { public Banana() { super("Banana"); } } public class Apple extends Fruit { public Apple() { super("Apple"); } } public class Grape extends Fruit { public Grape() { super("Grape"); } }
Abstract Class Rationale
The Fruit
class is abstract to provide common functionality (like name
) and establish a clear inheritance structure. An interface might be preferable if multiple inheritance or simpler contracts are needed. This warrants further discussion!
Step 2: Creating a Generic Shopping Cart
Now, let's build a ShoppingCart
class using generics to hold any fruit type while maintaining type safety.
import java.util.ArrayList; public class ShoppingCart<T extends Fruit> { // Restricts to Fruit and subclasses private ArrayList<T> items = new ArrayList<>(); public void addItem(T item) { items.add(item); } public void removeItem(T item) { items.remove(item); } public void displayItems() { for (T item : items) { System.out.println(item.getName()); } } }
T extends Fruit
ensures only Fruit
or its descendants can be added, preventing type errors.
Step 3: Using the Shopping Cart
Let's see how to use ShoppingCart
with our fruit objects.
public class Main { public static void main(String[] args) { ShoppingCart<Fruit> fruitCart = new ShoppingCart<>(); // Adding fruits fruitCart.addItem(new Banana()); fruitCart.addItem(new Apple()); fruitCart.addItem(new Grape()); // Displaying contents System.out.println("Shopping Cart:"); fruitCart.displayItems(); // Removing an item fruitCart.removeItem(new Apple()); // Removal based on object equality (equals() can be overridden) System.out.println("\nAfter removing Apple:"); fruitCart.displayItems(); } }
Advantages of Generics
-
Type Safety: Restricting
T
prevents adding incorrect types. -
Flexibility: The cart handles any
Fruit
type, promoting reusability. - No Casting: Retrieving items requires no casting, reducing runtime errors.
Conclusion
This Fruit
hierarchy and ShoppingCart
example demonstrates the power and flexibility of Java generics. Generics enhance code clarity and maintainability, making them invaluable for Java developers at all levels.
? References
- Java Generics Documentation
- Effective Java (Joshua Bloch)
? Connect With Me
- GitHub
- Portfolio
The above is the detailed content of Understanding Generics in Java: A Shopping Cart Example with Custom Classes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment