tvdhout

Generic Class vs generic method

May 15th, 2020
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. package main;
  2.  
  3. interface MyGenericInterface<X, Y> {
  4.     // Now the generic types X, and Y are defined in the scope of this entire interface and we can use them
  5.     X awesomeMethod(Y argument);  // awesomeMethod will return something of type X, which is still unknown at this point
  6. }
  7.  
  8. interface MyNormalInterface {
  9.     <X,Y> X coolMethod(MyGenericInterface<X,Y> generic, Y argument);
  10.  
  11.     // Here we define the generics in the declaration of a method. The generic types X and Y can only be used in
  12.     // the context of this method.
  13.     // Trying to create another abstract method like this will fail:
  14.     // X anotherMethod(Y arg);
  15.     // because the generics X and Y are not defined here
  16.  
  17.     // The interface is implemented without resolving the generics
  18. }
  19.  
  20. class MyClassOne implements MyGenericInterface<Void, String>{
  21.     // Classes that implement the generic interface should resolve these generics to actual classes
  22.     @Override
  23.     public Void awesomeMethod(String argument) {
  24.         System.out.println(argument);
  25.         return null;
  26.     }
  27. }
  28.  
  29. class MyClassTwo implements MyNormalInterface{
  30.     // Classes that implement the interface that doesn't have generics itself but some methods do don't resolve the
  31.     // generics.
  32.  
  33.     @Override
  34.     public <X, Y> X coolMethod(MyGenericInterface<X, Y> generic, Y argument) {
  35.         return generic.awesomeMethod(argument);
  36.     }
  37.     // Here we need to define the generics again for this method, because they weren't defined by the class, but we need
  38.     // them for this method. Define them like we did in the interface.
  39.  
  40.     // When calling this method with a concrete class that implements MyGenericInterface (and has therefor resolved the
  41.     // generics), the generics will be resolved for this method. For example, with a MyClassOne X will become Void and
  42.     // Y will become String.
  43. }
  44.  
  45. class Main2{
  46.     public static void main(String[] args){
  47.         MyClassOne classOne = new MyClassOne();  // aka Visitor
  48.         MyClassTwo classTwo = new MyClassTwo();  // aka Visitable
  49.         classTwo.coolMethod(classOne, "Hello World!");
  50.         // OUTPUT:
  51.         // Hello World!
  52.     }
  53. }
Add Comment
Please, Sign In to add comment