Java Generic Constructors

Example

It is possible for constructors to be generic, even if their class is not. For example, consider the following short program:


class MyClass {//  ww w  .j  a  v a  2  s .  co m
  private double val;

  <T extends Number> MyClass(T arg) {
    val = arg.doubleValue();
  }

  void showval() {
    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.showval();
    test2.showval();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use generic wildcard arguments
  2. Syntax for Java Generic Parameter Wildcard
  3. Example - an upper bound for a wildcard
  4. How to use generic bounded wildcards
Home »
  Java Tutorial »
    Java Langauge »
      Java Generics
Java Generic Type
Java Generic Bounded Types
Java Generic Method
Java Generic Constructors
Java Generic Parameter Wildcard
Java Generic interface
Java Raw Types and Legacy Code
Java Generic Class Hierarchies
Java generic types cast
Java Generic Restrictions