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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
