Generic Types are Classes or Interfaces that uses Generics

Let’s convert this interface:

public interface SomeBehaviour {
  Object behaviour(Object a, Object b);
}

To a Generic Type Interface:

public interface SomeBehaviour<T> {
  T behaviour(T a, T b);
}

What is <T>?

The angle brackets are the syntax for declaring that this Class/Interface uses generics.

T is known as a generic type parameter, which is just a placeholder for an actual object type!
The name is kinda self explanatory…

There’s nothing special about the character T. The code bellow is perfectly valid!

public interface SomeBehaviour<hehe> {
  hehe behaviour(hehe a, hehe b);
}

How do we use generics?

Simply substitute T for the chosen type!

public class MyImplementation implements SomeBehaviour<String> {
	@Override
    String behaviour(String a, String b) {
        //... implementation details
    }
}
// or! 
public abstract class MyAbstractImplementation<T> implements SomeBehaviour<T> {
	@Override
	String behaviour(T a, T b);
}

What does that do?

By using generics we can now have explicit type safety! The SomeBehaviour interface now inherently forces its implementations to specify a type T and ensures that both parameters of the behaviour function and its return type are of the type that was specified.

We can even accept multiple generic types!

public interface AnotherBehaviour<T, S> {
  void behaviour1(T a, S b);
  S behaviour2(T a);
}

This has its uses in Interfaces such as Map<K,V>! Where the key and value may be different types!

What’s Next?

java-generic-raw-types