Building Generic Classes in Java

by | Apr 11, 2021 | Java

Home » Java » Building Generic Classes in Java

Syntax

When dealing with generic programming in Java, ‘< Element Type >’ is used in the declaration. This is because the exact data type is not known. Once you have defined a generic class, the following syntax can be used to create objects of the generic class.

//To create objects of a generic class

BaseType <Type> obj = new BaseType <Type> ()

The only difference between normal object creations and generic class object creations is that you cannot use any primitive type in the type list. This means that ‘int’, ‘char’, and ‘double’ cannot be used.

Sample Code

//The following code demonstrates the working of user-defined classes.
/The ‘<>’ parameter needs to be specified.
class Test <T>
{
//Declaring an object of Type T
T obj;
Test (T obj)
{
this.obj = obj;
}
public T getObject()
{
return this.obj;
}
}
class Main
{
public static void main (String args[] )
{
Test <Integer> iObj = new Test <Integer> (15);
System.out.println (iObj.getObject());
Test <String> sObj = new Test <String> (“Hello World”);
System.out.println(sObj.getObject());
}
}

 

OUPUT

15

Hello World

Type Parameters in Generic Classes

class Test <T, U>
{
T obj1;
U obj2;
Test (T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
class Main
{
public static void main (String args [])
{
Test <String, Integer> obj = new Test<String, Integer> (“Hello”, 15);
obj.print();
}
}

 

OUTPUT

Hello
15

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author