Interfaces with Generics in Java


Create a Java program to demonstrate the use of interfaces with generics

  • Container<T> is a generic interface with a generic type parameter T. It declares two methods: getValue() to get the value stored in the container and setValue(T value) to set the value of the container.
  • MyContainer<T> is a generic class that implements the Container<T> interface. It has a type parameter T which is used to define the type of value stored in the container.
  • In the Main class, an instance of MyContainer<Integer> is created, specifying Integer as the type parameter. An integer value of 42 is then set using the setValue method. Finally, the value is retrieved using the getValue method and printed to the console.

Source Code

interface Container<T>
{
	T getValue();
	void setValue(T value);
}
 
class MyContainer<T> implements Container<T>
{
	private T value;
 
	@Override
	public T getValue()
	{
		return value;
	}
 
	@Override
	public void setValue(T value)
	{
		this.value = value;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Container<Integer> container = new MyContainer<>();
		container.setValue(42);
		System.out.println("Value : " + container.getValue());
	}
}

Output

Value : 42

Example Programs