Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package merjavabasics;
- /**
- * @author Meredith
- * Generics ..wooo.*/
- public class MerGenerics<T>{
- static interface Eatable{}
- static interface Drinkable{}
- static class Food{}
- static class MilkShake extends Food implements Eatable,Drinkable{}
- /* This says that MerGenericsJr extends MerGenerics, and it has a
- * different type param, U, which extends Number and implements
- * Eatable and Drinkable.
- * Because MerGenericsJr still extends MerGenerics<T>,
- * it may also make use of T.*/
- public class MerGenericsJr<U extends Food & Eatable & Drinkable> extends MerGenerics<T>
- {
- @Override
- public T METHOD(T t){
- System.out.println("Returning a "+t.getClass());
- return t;
- }
- /*Defining generic type S on the fly*/
- public <S extends T> T STMETHOD(S s)
- {
- return (T)s;
- }
- /*compiler doesn't complain on this useless generic:
- pointless definition of local generic S never used*/
- public <S extends T> int method(String s)
- {
- return 5;
- }
- }
- public T METHOD(T t){
- System.out.println("Returning a "+t.getClass());
- return t;
- }
- public static void main(String[] args)
- {
- System.out.println(new MerGenerics<Number>().METHOD(3).getClass());
- System.out.println(new MerGenerics<Object>().METHOD(5).getClass());
- System.out.println(new MerGenerics<Number>().new MerGenericsJr<MilkShake>().METHOD(5).getClass());
- System.out.println(new MerGenerics<Throwable>().new MerGenericsJr<MilkShake>().STMETHOD(new Exception("whatever.")).getClass());
- }
- /*OUTPUT:
- Returning a class java.lang.Integer
- class java.lang.Integer
- Returning a class java.lang.Integer
- class java.lang.Integer
- Returning a class java.lang.Integer
- class java.lang.Integer
- class java.lang.Exception
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement