Generics Flashcards
1
Q
- Generic type declarations can be used as…
- What are the 4 possible constraints for these declarations?
A
- Fields
- Parameters
- Local variables
- Return types
<Type>
<?>
<? extends Type>
<? super Type>
2
Q
- What are generics?
- Can a generic type be passed to another generic type?
A
- Generics are parameterized classes, interfaces, or methods
- Yes
MyGeneric<T> {...} MyOtherGeneric<U> {...} MyGeneric<MyOtherGeneric<SomeClass>>
3
Q
- What is the syntax for a generic constructor?
- Is the generic constructor type parameter the same as its generic class parameter?
- Can a generic constructor be used inside a non-generic class?
A
<T> ConstructorName(T param) {...}
- No
- Yes
4
Q
Can a non-generic class be a superclass of a generic class?
A
Yes
5
Q
- What is the syntax for a generic method?
- Is the generic method type parameter the same as its generic class parameter?
- Can a generic method be defined inside a non-generic class?
- Can a generic method be static or non-static?
A
<T> T method(T param) {...} <T> ReturnType method(T param) {...}
- No
- Yes
- Yes
6
Q
What is the syntax for a generic class that implements a generic interface?
A
interface MyGenericInterface<T> {...} class MyGenericClass<T> implements MyGenericInterface<T> {...}
7
Q
- When defining a generic class, what is the syntax to bind a generic type parameter to another class and interfaces?
A
class MyGeneric<T extends ClassName & InterfaceName, InterfaceName2> {...}
ClassName must always be first
8
Q
Legal or illegal?
class A {...} class B {...} class MyGeneric<T> {...} MyGeneric<B> b = new MyGeneric<>(); MyGeneric<A> a = b;
A
Illegal. Even though B extends A, MyGeneric<A>
has no relationship to MyGeneric<B>
9
Q
What is type erasure?
A
Type erasure is the process whereby the Java compiler erases all of the generic type parameters and replaces them with Object if unbounded or with their bounded type if bounded
10
Q
Legal or illegal?
MyGeneric<T>[] arr;
A
Illegal
11
Q
Can a generic class define static parameterzed members?
A
No, but generic methods can be static