Generics lecture
-
Upload
bradford-bazemore -
Category
Software
-
view
54 -
download
0
Transcript of Generics lecture
1
Generics <? super Java>By Brad Bazemore
2
Create... a box interface
− You can put into the box− You can take out of box− NOTE: needs to be able to handle ALL
possible types (not just primitives!)
GO!
3
Generic Programing
generic programming is a style of computer programming
written in terms of to-be-specified-later instantiated when needed for specific
types provided as parameters
4
Ex1
Given N data structures Given M algorithms If we want an algo for every data struct we
wind up with NM methods− NOTE: this is BAD
Using generics we end up with only N+M methods
− NODE: this is GOOD
5
Java Generics
6
What are they for?
"a type or method to operate on objects of various types while providing compile-time type safety." (Java Programming Language)
Basically...
− IT MAKES LIFE BETTER!!!
7
QUIZ!
If my program has 3 types of data structures and 5 types of algorithms...
1)How many methods will there be with NO generics?
2)How many methods will there be WITH generics?
GO!
8
The Syntax
ObjectName <Type Variable> Ex2
− ArrayList<String> L=new ArrayList<String>();
Attention Test
− Create a method signature for the put operation for a box, and it takes a generic of some kind
GO!
9
Lo Pi Hi
Lets take it up a notch! Ok so there is a catch, if I say <Number>
− Integer, Float, ect. It will not work!!! Why you ask? Attention Test
QUIZ!
10
Quiz
How do you implement a method with generic type that accepts all subtypes of Number?
11
Now that I have you attention
The fancy word for this is “variance” But so you can see the big picture Covariant: converting from a specialized
type (Cats) to a more general type (Animals): Every cat is an animal.
Contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?
Invariant: not able to convert.
12
So how to make this work...
Using the Java wild card “?”− Yes it is the
The basic idea is this− < ? extends T >− < ? super T >
Extends means all subtypes of T Super means all super types of T
13
Ex3
14
See?
Any Questions?
NOTE: there is a lab