As we know, java is a strongly typed class. It expects every single object instance or class it runs into to be specified a type.

And that’s fine if your application works as a single standalone application that does not interact with any third part source codes. Reality is, it doesn’t really work that way and most likely you might be interacting with other external sources.

Let’s say we have the following code:

public String getVal(String val){
	  return val;
	}

We are assuming this function will return the string in all scenarios. Totally fine but if we are working with third party code, this function can be returning something different.

Enters generic.

Generic allow users to parameterize classes, methods or interfaces to support one or more types. This can be one of any class type, any child class of a specified generic type, or a parent class of a specified generic type.

Here is a basic example of a generic class:

public class GenericsClass<T> {

		private T t;

		public T get(){
			return t;
		}

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

	}

#java #java8 #core-java

What is Generics in Java?
2.10 GEEK