JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Generic Constructors Example

April 25, 2014 by Krishna Srinivasan Leave a Comment

Generic is one of the useful language feature introduced from Java 5.0. There are many great features as part of the Generics is not fully utilized by the programmers. One such instance is the use of generic constructors. This example shows how to use the generic with constructor and takes the different type arguments.

In the below example, I have used the generic type T extends Number for constructor definition and also used “T” as the constructor argument. Here while invoking the constructor, any subclass can be passed to the argument which will be acceptable by that constructor.

Lets look at the simple example which extends the Number class and takes its sub classes Integer, Float, Double and Long as the arguments.

GenericExample.java

[code lang=”java”]
package javabeat.net.core;

/**
* Generic Constructor Example
*
* @author Krishna
*
*/
public class GenericExample {
<T extends Number> GenericExample(T value) {
if (value instanceof Integer){
System.out.println("Integer Value : " + value);
}
if (value instanceof Float){
System.out.println("Float Value : " + value);
}
if (value instanceof Double){
System.out.println("Double Value : " + value);
}
if (value instanceof Long){
System.out.println("Long Value : " + value);
}
}
public static void main(String[] args) {
//Invoke with integer value
GenericExample example = new GenericExample(12);

//Invoke with float value
example = new GenericExample(12.0F);

//Invoke with double value
example = new GenericExample(12.0);

//Invoke with long value
example = new GenericExample(12L);
}
}
[/code]

Output…

[code]
Integer Value : 12
Float Value : 12.0
Double Value : 12.0
Long Value : 12
[/code]

Filed Under: Java Tagged With: Java Generics

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved