Mega Code Archive

 
Categories / Java Tutorial / Generics
 

Casting within a generic class hierarchy

You can cast one instance of a generic class into another only if the two are otherwise compatible and their type arguments are the same. class Gen<T> {     T ob;         Gen(T o) {       ob = o;     }        T getObject() {       return ob;     }   }     class Gen2<T> extends Gen<T> {    Gen2(T o) {      super(o);    }  }    public class MainClass {     public static void main(String args[]) {       Gen<Integer> intObject = new Gen<Integer>(88);      Gen2<Long> longObject = new Gen2<Long>(99L);         //longObject = (Gen2<Long>)intObject;     }   }