Java TOPIC 18 – GENERICS LESSON NOTE WHY
NOW? We need to
learn about Generics now so that we can make use of the built-in data
structures in the Java Collections.
This lesson will prepare us for that. OBJECT CLASS (REVIEW) All classes
in Java automatically extend the Object class. By consequence, all objects inherit all datafields & methods in the Object class. Recall that the toString() method can be
called on any object – that is because it is in the Object class and is
inherited. Using polymorphism,
we can also do this: Object obj
= new AnyClass(); OBJECT DATAFIELD When creating
a class, we can have a datafield of type Object. This can in turn actually hold any type of
object.
Being able to
create a class that can hold any type of object is very useful – especially
when it comes to specialized classes that are used specifically to organize
different types of data (aka, data structures). PROBLEM The above
approach works well. It doesn't
include any generics. So why do we
need generics? There is a
problem that arises with the above situation.
Because the Object datafield can be any
object, Java has no way of testing if the programmer is being
consistent. So the user might be
storing a String and then expecting a Point from that datafield. That error
would only be caught at run-time and can lead to complications. So, as Java continued to evolve, the idea
of generics was included to deal
with this problem. GENERICS The concept
of generics allows us to specify a consistent type of data that will be used
throughout a class. Classes that use
generics are called generic classes and are declared in the following way: public className<T> { … } Where T
specifies the type of the data that will be used. So, anywhere in the class, we can use T to
ensure consistency in regards to the data type.
NAMING CONVENTION Does the
generic parameter inside the class have to be "T"? No, it doesn't. It can be anything. However, java convention is to use a single
upper case letter. And T is used most
because it is short for "type". MULTIPLE GENERIC
PARAMETERS You can have
multiple generic paramaters if you'd like. A generic class with two generic parameters
would look like: public className<T, U> { … } And inside
the class, T and U would be used to refer to the two types specified when the
object was created.
Source:
https://docs.oracle.com/javase/tutorial/java/generics/types.html |
|||
|