Generics in Java

Guided by Bipin Ajay
Founder of Tech Jitendra .

Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.

// To create an instance of generic class BaseType <Type> obj = new BaseType <Type>() Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.// A Simple Java program to show working of user defined // Generic classes // We use < > to specify Parameter type classTest<T> { // An object of type T is declared T obj; Test(T obj) {  this.obj = obj;  }  // constructor publicT getObject()  { returnthis.obj; } } // Driver class to test above classMain { publicstaticvoidmain (String[] args) { // instance of Integer type Test <Integer> iObj = newTest<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test <String> sObj = newTest<String>("GeeksForGeeks"); System.out.println(sObj.getObject()); } }output 15 Geek for Geek

Thanking you

Tech Jitendra

Published by Tech Jitendra Direct Investing

Tech Jitendra Direct Investing (TJDI) Empoworing Your Wealth

Join the Conversation

  1. Tech Jitendra Direct Investing's avatar

2 Comments

Leave a comment

Design a site like this with WordPress.com
Get started