Skip to content
Related Articles

Related Articles

Improve Article

Generic Constructors and Interfaces in Java

  • Last Updated : 28 Jan, 2021

Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable.

Generic constructors are the same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed.  Constructors can be invoked with any type of a parameter after defining a generic constructor. A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is same as the class name. Constructors can be Generic, despite its class is not Generic. 

Implementation: 

Example

Java




// Java Program to illustrate Generic constructors
  
// Importing input output classes
import java.io.*;
  
// Class 1
// Generic class
class GenericConstructor {
    // Member variable of this class
    private double v;
  
    // Constructor of this class where
    // T is typename and t is object
    <T extends Number> GenericConstructor(T t)
    {
        // Converting input number type to double
        // using the doubleValue() method
        v = t.doubleValue();
    }
  
    // Method of this class
    void show()
    {
        // Print statement whenever method is called
        System.out.println("v: " + v);
    }
}
  
// Class 2 - Implementation class
// Main class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Display message
        System.out.println("Number to Double Conversion:");
  
        // Creating objects of type GenericConstructor i.e
        // og above class and providing custom inputs to
        // constructor as parameters
        GenericConstructor obj1
            = new GenericConstructor(10);
        GenericConstructor obj2
            = new GenericConstructor(136.8F);
  
        // Calling method - show() on the objects
        // using the dot operator
        obj1.show();
        obj2.show();
    }
}
Output



Number to Double Conversion:
v: 10.0
v: 136.8000030517578

Output explanation: Here GenericConstructor() states a parameter of a generic type which is a subclass of Number. GenericConstructor() can be called with any numeric type like Integer, Float, or Double. So, in spite of GenericConstructor() is not a generic class, its constructor is generic.

Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class. These include all abstract methods only, have static and final variables only. The only reference can be created to interface, not objects, Unlike class, these don’t contain any constructors, instance variables. This involves the “implements” keyword. These are similar to generic classes.

The benefits of Generic Interface are as follows:

  1. This is implemented for different data types.
  2. It allows putting constraints i.e. bounds on data types for which interface is implemented.

Syntax:

interface interface-Name < type-parameter-list > {//....}

class class-name <type-parameter-list> implements interface-name <type-arguments-list> {//...}

Implementation: The following example creates an interface ‘MinMax’ which involves very basic methods such as min(), max() just in order to illustrate as they return the minimum and maximum values of given objects.

Example

Java




// Java Program to illustrate Generic interfaces
  
// Importing java input output classes
import java.io.*;
  
// An interface that extends Comparable
interface MinMax<T extends Comparable<T> > {
    // Declaring abstract methods
    // Method with no body is abstract method
    T min();
    T max();
}
  
// Class 1 - Sub-class
// class extending Comparable and implementing interface
class MyClass<T extends Comparable<T> >
    implements MinMax<T> {
  
    // Member variable of 'MyClass' class
    T[] values;
  
    // Constructor of 'MyClass' class
    MyClass(T[] obj) { values = obj; }
  
    // Now, defining min() and max() methods
    // for MimMax interface computation
  
    // Defining abstract min() method
    public T min()
    {
        // 'T' is typename and 'o1' is object_name
        T o1 = values[0];
  
        // Iterating via for loop over elements using
        // length() method to get access of minimum element
        for (int i = 1; i < values.length; i++)
            if (values[i].compareTo(o1) < 0)
                o1 = values[i];
  
        // Return the minimum element in an array
        return o1;
    }
  
    // Defining abstract max() method
    public T max()
    {
        // 'T' is typename and 'o1' is object_name
        T o1 = values[0];
  
        // Iterating via for loop over elements using
        // length() method to get access of minimum element
        for (int i = 1; i < values.length; i++)
            if (values[i].compareTo(o1) > 0)
                o1 = values[i];
  
        // Return the maximum element in an array
        return o1;
    }
}
  
// Class 2 - Main class
// Implementation class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Custom entries in an array
        Integer arr[] = { 3, 6, 2, 8, 6 };
  
        // Create an object of type as that of above class
        // by declaring Integer type objects, and
        // passing above array to constructor
        MyClass<Integer> obj1 = new MyClass<Integer>(arr);
  
        // Calling min() and max() methods over object, and
  
        // printing the minimum value from array elements
        System.out.println("Minimum value: " + obj1.min());
  
        // printing the maximum value from array elements
        System.out.println("Maximum value: " + obj1.max());
    }
}
Output
Minimum value: 2
Maximum value: 8

Output explanation: Here interface is declared with type parameter T, and its upper bound is Comparable which is in java.lang. This states how objects are compared based on type of objects. Above T is declared by MyClass and further passed to MinMax as MinMax needs a type that implements Comparable and implementing class(MyClass) should have same bounds.  

Note: Once a bound is established, it is not necessary to state it again in implements clause. If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :