search
HomeJavajavaTutorialUnderstanding Generics in Java: A Shopping Cart Example with Custom Classes

Understanding Generics in Java: A Shopping Cart Example with Custom Classes

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

  1. Type Safety: Restricting T prevents adding incorrect types.
  2. Flexibility: The cart handles any Fruit type, promoting reusability.
  3. 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

  • LinkedIn
  • 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

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

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment