Generic Constructors

In this chapter you will learn:

  1. How to create a generic constructor

Create a generic constructor

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

class MyClass {/*from jav a  2 s .  com*/
  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();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use generic wildcard arguments
  2. How to use generic bounded wildcards
Home » Java Tutorial » Generics
Generic Type
Generic Bounded Types
Generic Method
Generic Constructors
Wildcard
Generic interface
Raw Types and Legacy Code
Generic Class Hierarchies
Cast generic types
Generic Restrictions