class
Generic Constructor
This is an example of how to use a generic constructor of a class. In order to see how a generic constructor works we have created a class with a generic constructor and then created instances of the class to use its constructor.
GenericClass
class has a double field, val.- It has a constructor using an object of
T
class that extendsNumber
, sets its double field to the object’s double value, usingdoubleValue()
API method of Number and returns the object. - It has a method
void value()
that prints the double field of the class. - We create a new instance of GenericClass with a given Integer object and another instance of
GenericClass
with a given Float object, and call values() method for both objects. - In both cases the double value of the fields are returned.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; class GenericClass { private double val; <T extends Number> GenericClass(T arg) { val = arg.doubleValue(); } void values() { System.out.println("val: " + val); } } public class GenericConstructor { public static void main(String args[]) { GenericClass c1 = new GenericClass(100); GenericClass c2 = new GenericClass(123.5F); c1.values(); c2.values(); } }
Output:
val: 100.0
val: 123.5
This was an example of how to use a generic constructor of a class in Java.