Java Generic Raw Types and Legacy Code

Introduction

Java allows a generic class to be used without any type arguments.

This creates a raw type for the class.


// Demonstrate a raw type. 
class MyClass<T> {
  T ob; // declare an object of type T

  // Pass the constructor a reference to
  // an object of type T.
  MyClass(T o) {// ww w .j  av a 2  s .  c  o  m
    ob = o;
  }

  // Return ob.
  T getob() {
    return ob;
  }
}

// Demonstrate raw type.
public class Main {
  public static void main(String args[]) {

    MyClass<Integer> iOb = new MyClass<Integer>(88);

    MyClass<String> strOb = new MyClass<String>("Generics Test");

    MyClass raw = new MyClass(new Double(98.6));

    // Cast here is necessary because type is unknown.
    double d = (Double) raw.getob();
    System.out.println("value: " + d);

  }
}



PreviousNext

Related