Java generic types cast

In this chapter you will learn:

  1. How to cast generic types
  2. Example - Java generic types cast

Description

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

Example

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


class Gen<T> {
  T ob;//from   w  w  w.  jav a2 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   w w w .  jav a2  s.com

  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 »
    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