×

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

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.