Lecture 4 - Introduction To Generics: There Are Two Types of Variables in Java: A Reference Variable
Lecture 4 - Introduction To Generics: There Are Two Types of Variables in Java: A Reference Variable
Lecture 4 –
Introduction to
Generics
• A reference variable:
– Stores the memory location of an object.
• A primitive variable:
– Directly stores the value.
int x = 50;
– x is a primitive variable: it doesn’t store a memory location, but
rather the number 50.
1
4/3/18
2
4/3/18
Recap: Autoboxing/auto-unboxing
Generics
• A generic class is written by placing a generic type
parameter (for example, T) in angle brackets immediately
after the class name in the class header.
3
4/3/18
Generics - example
public T getData()
{
return data;
}
}
4
4/3/18
Generics
Once we instantiate a generic object with a type argument,
any of its methods that accept a parameter of that generic
type only accept arguments of the same type as the type
argument:
Sample<String> mySample = new Sample<>();
mySample.setData("Some Data"); // allowed!
mySample.setData(5); // not allowed!
String data = mySample.getData(); // allowed
int data = mySample.getData(); // not allowed!
Generics
mySample.setData(1); // allowed!
int value = mySample.getData(); // also allowed!
5
4/3/18
Generics - notes
Within the definition of a class name<T>, where T is a
generic type parameter,
• <T> follows the identifier name in the class’s header
• <T> does not follow the names of the constructors in their
definitions
• T—not <T>—can be a data type of data fields, method
parameters, and local variables, and it can be a return type of
methods
6
4/3/18