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

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

Barbara Streisand
Release: 2025-01-20 22:14:13
Original
1000 people have browsed it

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:

<code class="language-java">String[] fruits = new String[3];
fruits[0] = "Apple";  // Correct
fruits[1] = 123;      // Compile-time error</code>
Copy after login

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.

<code class="language-java">// 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");
    }
}</code>
Copy after login

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.

<code class="language-java">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());
        }
    }
}</code>
Copy after login

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.

<code class="language-java">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();
    }
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template