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 extends Number, sets its double field to the object’s double value, using doubleValue() 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button