Java Generic Constructors

Introduction

We can create generic constructors, even if their class is not.

For example:

// Use a generic constructor. 
class MyClass { /*  w w w. ja  va2 s. co  m*/
  private double val; 
 
  public <T extends Number> MyClass(T arg) { 
    val = arg.doubleValue(); 
  } 
 
  public void display() { 
    System.out.println("val: " + val); 
  } 
} 
 
public class Main { 
  public static void main(String args[]) { 
 
    MyClass test = new MyClass(100); 
    MyClass test2 = new MyClass(123.5F); 
 
    test.display(); 
    test2.display(); 
  } 
}



PreviousNext

Related