Skip to content

Instantly share code, notes, and snippets.

@ThierryAbalea
Last active December 5, 2019 17:23
Show Gist options
  • Save ThierryAbalea/a48002823945305fbc3410380d879206 to your computer and use it in GitHub Desktop.
Save ThierryAbalea/a48002823945305fbc3410380d879206 to your computer and use it in GitHub Desktop.
Java Generics Quiz
public class Generics1 {
static class GenType<T> {}
static class TypeA {}
static class TypeB extends TypeA {}
static class TypeC extends TypeB {}
static <T> void method(GenType<T> arg1, T arg2) {}
public static void main(String[] args) {
GenType<TypeA> arg1A = new GenType<>();
GenType<TypeB> arg1B = new GenType<>();
GenType<TypeC> arg1C = new GenType<>();
TypeA arg2A = new TypeA();
TypeB arg2B = new TypeB();
TypeC arg2C = new TypeC();
method(arg1A, arg2A); // stmt 1
method(arg1A, arg2B); // stmt 2
method(arg1A, arg2C); // stmt 3
method(arg1B, arg2A); // stmt 4
method(arg1B, arg2B); // stmt 5
method(arg1B, arg2C); // stmt 6
method(arg1C, arg2A); // stmt 7
method(arg1C, arg2B); // stmt 8
method(arg1C, arg2C); // stmt 9
}
}
public class Generics2 {
static class GenType<T> {
void method1(T arg) {}
T method2() { return null; }
}
static class TypeA {}
static class TypeB extends TypeA {}
static class TypeC extends TypeB {}
static void method(GenType<? extends TypeB> arg) {
arg.method1(null); // stmt 1
arg.method1(new Object()); // stmt 2
arg.method1(new TypeA()); // stmt 3
arg.method1(new TypeB()); // stmt 4
arg.method1(new TypeC()); // stmt 5
Object object = arg.method2(); // stmt 6
TypeA typeA = arg.method2(); // stmt 7
TypeB typeB = arg.method2(); // stmt 8
TypeC typeC = arg.method2(); // stmt 9
}
public static void main(String[] args) {
method(new GenType<Object>()); // stmt 10
method(new GenType<TypeA>()); // stmt 11
method(new GenType<TypeB>()); // stmt 12
method(new GenType<TypeC>()); // stmt 13
}
}
/**
* Same code than Generics2, only the keyword "extends"
* have been replaced by "super"
*/
public class Generics3 {
static class GenType<T> {
void method1(T arg) {}
T method2() { return null; }
}
static class TypeA {}
static class TypeB extends TypeA {}
static class TypeC extends TypeB {}
static void method(GenType<? super TypeB> arg) {
arg.method1(null); // stmt 1
arg.method1(new Object()); // stmt 2
arg.method1(new TypeA()); // stmt 3
arg.method1(new TypeB()); // stmt 4
arg.method1(new TypeC()); // stmt 5
Object object = arg.method2(); // stmt 6
TypeA typeA = arg.method2(); // stmt 7
TypeB typeB = arg.method2(); // stmt 8
TypeC typeC = arg.method2(); // stmt 9
}
public static void main(String[] args) {
method(new GenType<Object>()); // stmt 10
method(new GenType<TypeA>()); // stmt 11
method(new GenType<TypeB>()); // stmt 12
method(new GenType<TypeC>()); // stmt 13
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment