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();
}
}
OutputNumber 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:
- This is implemented for different data types.
- 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());
}
}
OutputMinimum 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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read