Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main;
- interface MyGenericInterface<X, Y> {
- // Now the generic types X, and Y are defined in the scope of this entire interface and we can use them
- X awesomeMethod(Y argument); // awesomeMethod will return something of type X, which is still unknown at this point
- }
- interface MyNormalInterface {
- <X,Y> X coolMethod(MyGenericInterface<X,Y> generic, Y argument);
- // Here we define the generics in the declaration of a method. The generic types X and Y can only be used in
- // the context of this method.
- // Trying to create another abstract method like this will fail:
- // X anotherMethod(Y arg);
- // because the generics X and Y are not defined here
- // The interface is implemented without resolving the generics
- }
- class MyClassOne implements MyGenericInterface<Void, String>{
- // Classes that implement the generic interface should resolve these generics to actual classes
- @Override
- public Void awesomeMethod(String argument) {
- System.out.println(argument);
- return null;
- }
- }
- class MyClassTwo implements MyNormalInterface{
- // Classes that implement the interface that doesn't have generics itself but some methods do don't resolve the
- // generics.
- @Override
- public <X, Y> X coolMethod(MyGenericInterface<X, Y> generic, Y argument) {
- return generic.awesomeMethod(argument);
- }
- // Here we need to define the generics again for this method, because they weren't defined by the class, but we need
- // them for this method. Define them like we did in the interface.
- // When calling this method with a concrete class that implements MyGenericInterface (and has therefor resolved the
- // generics), the generics will be resolved for this method. For example, with a MyClassOne X will become Void and
- // Y will become String.
- }
- class Main2{
- public static void main(String[] args){
- MyClassOne classOne = new MyClassOne(); // aka Visitor
- MyClassTwo classTwo = new MyClassTwo(); // aka Visitable
- classTwo.coolMethod(classOne, "Hello World!");
- // OUTPUT:
- // Hello World!
- }
- }
Add Comment
Please, Sign In to add comment