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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button