Advertisement
MerAll

Generics

Jul 13th, 2014
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package merjavabasics;
  2.  
  3. /**
  4.  * @author Meredith
  5.  * Generics ..wooo.*/
  6. public class MerGenerics<T>{
  7.  
  8.     static interface Eatable{}
  9.     static interface Drinkable{}
  10.     static class Food{}
  11.     static class MilkShake extends Food implements Eatable,Drinkable{}
  12.  
  13.     /* This says that MerGenericsJr extends MerGenerics, and it has a
  14.      *  different type param, U, which extends Number and implements
  15.      *  Eatable and Drinkable.
  16.      *  Because MerGenericsJr still extends MerGenerics<T>,
  17.      *  it may also make use of T.*/
  18.     public class MerGenericsJr<U extends Food & Eatable & Drinkable> extends MerGenerics<T>
  19.     {
  20.         @Override
  21.         public T METHOD(T t){
  22.             System.out.println("Returning a "+t.getClass());
  23.                 return t;
  24.            
  25.         }
  26.         /*Defining generic type S on the fly*/
  27.         public <S extends T> T STMETHOD(S s)
  28.         {
  29.             return (T)s;
  30.         }
  31.         /*compiler doesn't complain on this useless generic:
  32.           pointless definition of local generic S never used*/
  33.         public <S extends T> int method(String s)  
  34.         {
  35.             return 5;
  36.         }
  37.        
  38.        
  39.     }
  40.    
  41.    
  42.     public T METHOD(T t){
  43.         System.out.println("Returning a "+t.getClass());
  44.             return t;
  45.        
  46.     }
  47.    
  48.    
  49.    
  50.     public static void main(String[] args)
  51.     {
  52.         System.out.println(new MerGenerics<Number>().METHOD(3).getClass());
  53.         System.out.println(new MerGenerics<Object>().METHOD(5).getClass());
  54.        
  55.         System.out.println(new MerGenerics<Number>().new MerGenericsJr<MilkShake>().METHOD(5).getClass());
  56.         System.out.println(new MerGenerics<Throwable>().new MerGenericsJr<MilkShake>().STMETHOD(new Exception("whatever.")).getClass());
  57.        
  58.     }
  59.    
  60.     /*OUTPUT:
  61.         Returning a class java.lang.Integer
  62.         class java.lang.Integer
  63.         Returning a class java.lang.Integer
  64.         class java.lang.Integer
  65.         Returning a class java.lang.Integer
  66.         class java.lang.Integer
  67.         class java.lang.Exception
  68.      */
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement