×

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows.

// To create an instance of a generic class 
BaseType <T> obj = new BaseType <T>()

T isn't really a class. The usage of your class TemplateBuilder determines it at compile time. Consider it merely as a placeholder for a variety of potential kinds, one of which is "selected" based on your specific situation.

Take a look at the following example:

Imagine you want to create a class called Box that can store a certain type of item (the type of object to hold inside the box), but you want to reuse it in multiple contexts to hold different sorts of objects.

As a result, rather than fixing the actual type that the Box can accept, you define it as follows:

public class Box<T> {


    private T t; // T stands for "Type"          


    public void set(T t) {
        this.t = t;
    }


    public T get() {
        return t;
    }
}

When you use it, you subsequently take the following actions:

Box<Integer> integerBox = new Box<Integer>();

Why not make Box take an Object?

In actuality, this was only possible after Java 1.5. The Collections framework incorporated this in order to provide further type-safety in these circumstances.

The whole idea is that you couldn't force a specific instance of your Box to retain just Integers if it didn't have this method and instead used Object. On the other hand, if you restricted it to using only integers, you would have to design a different sort of Box class if you wanted to use it for items like strings or other types of objects.

Before Java 1.5, objects like ArrayList took plain Objects; however, there were often cases of type safety broken at runtime because the program is assuming a list of Integer objects, and by mistake, somewhere, a String is inserted. Generics (through this magic T) force types without restricting what they might be.

In your case, T extends TemplateBuilder is going one step further and stating that whatever T is, it must be a class that extends TemplateBuilder. If that weren't there, it would be any class that extends Object (the universal base class of Java).

Custom Generics

  • Data structures always employ custom generics, such as when managing (storing/retrieving) lists of "things." 
  • Because custom generics embrace the polymorphism concepts, type checking is not necessary for the code to compile.
  • However, a class can store a list of things without having any relationship with the "thing(s)" it is storing, in contrast to the "conventional" Object Oriented principles of polymorphism (The Fundamental Object Oriented Principle where A is a super class of B class is not required).
  • You don't create distinct subclasses for each class of "things" you might want to store.

Consider the two unrelated classes listed below as an illustration. Despite being extremely simple, the following example illustrates the basic ideas behind custom generics:

/**
 *
 * Class A is a Custom Generic class that can be 'typed'
 * to any kind of class using diamond 'T' syntax. 
 * 
 */


class A<T> 
{   
  // The instance variable of the object type 'T' known at run time
  T theI;


  // The constructor passing the object type 'T' 
  A(T anI)
  {
    this.theI = anI;
  }


  // Method to return the object 'T'
  T getT()
  {
    return theI;
  }
}  

Below is the class B, which is unrelated to class A i.e., B does not extend A

/**
*
* Simple class which overrides the toString()
* method from Object's class toString() method 
* 
*/
class B 
{


  @Override
  public String toString()
  {
    return "B Object";
  }


  public static void main(String[] args)
  {
    A<B> a = new A<>(new B());


    System.out.println(a.getT());        
  }
}

In the Main method of class B above:

a.getT() returns the object 'T', which in this example is of type 'B' (This is an example of polymorphism).

a.getT() returns the object 'T', object instance C's method toString() gets IMPLICITLY called, as it is overriding Object's toString() method and prints "B Object".

The interesting aspect to note about Custom Generics and polymorphism is that:

In the context of custom generics, there are no constraints for a relationship among classes in order to execute polymorphism

e.g., Class B is unrelated to A above, i.e, and class B DOES not extend A.

In "traditional" object-orientated polymorphism principles, there is invariably a requirement constraint for classes to be related in some way. However, this is not required in custom generics.

Filename: B.java

/**
 *
 * Class A is a Custom Generic class that can be 'typed'
 * to any kind of class using diamond 'T' syntax. 
 * 
 */


/**
*
* Simple class which overrides the toString()
* method from Object's class toString() method 
* 
*/


class B 
{


  @Override
  public String toString()
  {
    return "B Object";
  }


  public static void main(String[] args)
  {
    A<B> a = new A<>(new B());


    System.out.println(a.getT());        
  }
}


class A<T> 
{   
  // The instance variable of the object type 'T' known at run time
  T theI;


  // The constructor passing the object type 'T' 
  A(T anI)
  {
    this.theI = anI;
  }


  // Method to return the object 'T'
  T getT()
  {
    return theI;
  }
}  

Output

Creating a custom generic class in java
public interface TemplateBuilder<T extends TemplateBuilder>

The above means that the TemplateBuilder interface can be typedinto any class that extends TemplateBuilder.

Let's assume SomeClass extends TemplateBuilder then the following is fine:

TemplateBuilder<SomeClass> tbRef = ... 
/* Using an Anonymous Inner Class reference to interface TemplateBuilder<SomeClass> */ 

Related Topics

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.