Cast generic types

In this chapter you will learn:

  1. How to cast generic types

How to cast generic types

You can cast one instance of a generic class into another only if the two are compatible and their type arguments are the same.

For example, assuming the foregoing program, this cast is legal:

class Gen<T> {
  T ob;/*from  j  a v  a 2 s.co  m*/

  Gen(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    iOb = (Gen<Integer>) iOb2;
  }
}

because iOb2 is an instance of Gen<Integer>. But, this cast:

class Gen<T> {
  T ob;/*from ja  v  a  2  s. c o m*/

  Gen(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

public class Main {
  public static void main(String args[]) {
    Gen<Integer> iOb = new Gen<Integer>(88);
    Gen2<Integer> iOb2 = new Gen2<Integer>(99);
    Gen2<String> strOb2 = new Gen2<String>("Generics Test");
    //iOb = (Gen<Long>) iOb2;//wrong
  }
}

is not legal because iOb2 is not an instance of Gen<Long>.

Next chapter...

What you will learn in the next chapter:

  1. Type Parameters Can't Be Instantiated
  2. What are restrictions on static members
  3. What are restrictions on generic array
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