Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Creating Generics Class to Store the Custom Objects Data

In this lesson, you will learn.

  • Generics Used to Store Custom Object Data
  • Example

 

The General Form of a Generic Class

Here is the syntax for declaring a generic class:

class class-name <type-param-list > 
{ 
     // …
}

 

Example

class Storage <T> 
{ 
     //Body of Class
}

 

Here is the full syntax for declaring a reference to a generic class and instance creation

class-name <type-arg-list > var-name = 
    new class-name <type-arg-list > (cons-arg-list);

 

Example

Storage<String> stringStorage = new Storage<String>();
                        //OR
Storage<String> stringStorage = new Storage<>();

 

Example-1: Storing Different Types of Data

Here’s an example of a Generic class in Java that can handle different types of data.

Consider a class called Storage, which is designed to store and retrieve objects of any type, like documents, images, or messages.

 

Generic Class: Storage <T>

This class uses a generic type parameter, <T>, which allows it to operate on various data types while maintaining type safety.

public class Storage<T> {
    private T item;

    public void store(T item) {
        this.item = item;
    }

    public T retrieve() {
        return item;
    }
}

 

Explanation

1. Generic Type <T>: This is a type parameter that can be replaced with any object type when an instance of Storage is created.

It allows the Storage class to be flexible yet type-safe.

 

2. store(T item): This method accepts an object of type T.

Whatever type is specified for an instance of a Storage, the store method will accept only that type of data. This ensures that the data stored is consistent.

 

3. retrieve(): This method returns the object stored in Storage.

Since the object is of type T, no casting is required when retrieving it, making the code safer and cleaner.

 

Using The Storage Class

To use this Storage class for different types, you simply instantiate it with the desired data type.

 

Storing String

Storage<String> stringStorage = new Storage<>();
stringStorage.store("Hello, World!");
String myString = stringStorage.retrieve();
System.out.println(myString);  
// Output: Hello, World!

 

Storing Integers

Storage<Integer> integerStorage = new Storage<>();
integerStorage.store(123);
Integer myInteger = integerStorage.retrieve();
System.out.println(myInteger);  // Output: 123

 

Storing Custom Objects

class User {
    String name;
    int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}

Storage<User> userStorage = new Storage<>();
userStorage.store(new User("John Doe", 30));
User myUser = userStorage.retrieve();
System.out.println(myUser);  
// Output: User{name='John Doe', age=30}

 

Example-2: Storing Different Types of Vehicles

We’ll create a Garage class that can accommodate different types of vehicles, such as cars, motorcycles, or even bicycles.

 

Generic Class: Garage<T>

The Garage<T> is a generic class designed to hold vehicles of any specified type.

This approach allows the same Garage class to be used for different types of vehicles without creating separate classes for each Vehicle type, thus promoting code reusability and maintainability.

Java Code Implementation

public class Garage<T> {
    private T vehicle;

    public void park(T vehicle) {
        this.vehicle = vehicle;
        System.out.println(vehicle + " has been parked in the garage.");
    }

    public T retrieve() {
        return vehicle;
    }
}

// Vehicle classes
class Car {
    private String model;

    public Car(String model) {
        this.model = model;
    }

    @Override
    public String toString() {
        return "Car{" + "model='" + model + ''' + '}';
    }
}

class Motorcycle {
    private String model;

    public Motorcycle(String model) {
        this.model = model;
    }

    @Override
    public String toString() {
        return "Motorcycle{" + "model='" + model + ''' + '}';
    }
}

class Bicycle {
    private String type;

    public Bicycle(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Bicycle{" + "type='" + type + ''' + '}';
    }
}

Example Usage

This section demonstrates how the Garage class can be instantiated for different vehicle types

public class Main {
    public static void main(String[] args) {
        Garage<Car> carGarage = new Garage<>();
        carGarage.park(new Car("Tesla Model S"));
        System.out.println(carGarage.retrieve());

        Garage<Motorcycle> motorcycleGarage = new Garage<>();
        motorcycleGarage.park(new Motorcycle("Harley-Davidson"));
        System.out.println(motorcycleGarage.retrieve());

        Garage<Bicycle> bicycleGarage = new Garage<>();
        bicycleGarage.park(new Bicycle("Mountain Bike"));
        System.out.println(bicycleGarage.retrieve());
    }
}

Output

Car{model='Tesla Model S'} has been parked in the garage.
Car{model='Tesla Model S'}
Motorcycle{model='Harley-Davidson'} has been parked in the garage.
Motorcycle{model='Harley-Davidson'}
Bicycle{type='Mountain Bike'} has been parked in the garage.
Bicycle{type='Mountain Bike'}

Explanation

  • Garage<T>: This class is generic and can hold any type of vehicle. By using the generic type T, it can flexibly adapt to any specific vehicle type, such as Car, Motorcycle, or Bicycle.
  • park(T vehicle): Adds a vehicle to the garage. The use of T ensures that only vehicles of a consistent type are added to a particular instance of Garage.
  • retrieve(): Returns the parked vehicle without the need for casting, since the type T is known and enforced at compile time.

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review