Chapter 19 Generics Dr. Clincy - Lecture
Example – How is it implemented ? public class GeometricObject { . Subclass Superclass public class Circle extends GeometricObject { . public class Rectangle extends GeometricObject { . The keyword extends tells the compiler that the subclass extends the superclass, thus, the subclass inherits the superclass’ methods Dr. Clincy ------ Lecture
Abstract Classes and Abstract Methods Since area and perimeter can be computed for all geometric objects, its better to define the getArea() and getPerimeter() methods in the SuperClass, GeometricObject – designated using the abstract modifier in the class header However, these methods cannot be implemented in the SuperClass, GeometricObject, because their implementation depends on the specific type of geometric object – these are called abstract methods – designated using the abstract modifier in the method header Dr. Clincy - Lecture 3
Motivations SuperClass Classes become more specific and concrete with each new subclass Moving from a subclass back up to a superclass, the classes become more general and less specific SubClass1 SubClass2 SubClassN Sometimes, a superclass is so general, it cannot be used to create any specific instance – such a class is referred to as an abstract class Dr. Clincy - Lecture 4
What is an Interface ? An interface is a classlike construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but the intent of an interface is to specify common behavior for objects. For example, given the classes fish, orange, apple and soup, we could use the interface edible to describe some common behavior or use. Instead of reinventing the wheel, we can use existing classes and methods to specify common behavior for objects Dr. Clincy - Lecture 5
The ArrayList Class – original “generic” class You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects. Various methods for the ArrayList class Dr. Clincy ------ Lecture
The Issue Let’s say we want a class and associated methods to be used for multiple object types – write the code once If you write the class so that any object type can be used, the problem is, we will have to cast our objects back to class we want, in order to use it (too much casting is not good code – prone to runtime errors – the worst errors)\ The above was the solution prior to JDK 1.5 (or Java 5) The benefit and intent of the ArrayList class was that it can hold any object type The benefit of the ArrayList was, we can determine how the ArrayList class will work without having to specify what objtect types the ArrayList holds Once we instantiate an instance of the ArrayList class, we would tell it the object type our ArrayList will work with – in this case, no other object type is allowed Recall - With this approach, we had to cast it back to the class we needed If it is incorrectly casted, you will get a runtime error To fix this problem, we need to be able to tell Java what our ArrayList object is at compile time (versus it appearing at runtime). After JDK 1.5, this capability is now provided No casting needed Dr. Clincy - Lecture
Generic Type Old Way (prior to JDK 1.5) ArrayList cities = new ArrayList (); ArrayList is known as a generic class with a generic type E. You can specify a concrete type to replace E when creating an ArrayList. For example, the following statement creates an ArrayList and assigns its reference to variable cities. This ArrayList object can be used to store strings. ArrayList<String> cities = new ArrayList<String>(); Either syntax will work ArrayList<String> cities = new ArrayList<>(); Dr. Clincy ------ Lecture
Why Generics? The key benefit of generics is to enable errors to be detected at compile time rather than at runtime. A generic class or method permits you to specify allowable types of objects that the class or method may work with. If you attempt to use the class or method with an incompatible object, a compile error occurs. Dr. Clincy - Lecture
What is Generics? Why Generics? Generics is the capability to parameterize types. With this capability, you can define a class or a method with generic types that can be substituted using concrete types by the compiler. Why Generics? The key benefit of generics is to enable errors to be detected at compile time rather than at runtime. A generic class or method permits you to specify allowable types of objects that the class or method may work with. If you attempt to use the class or method with an incompatible object, a compile error occurs. Dr. Clincy - Lecture
Generic Instantiation Generic Type Generic Instantiation Runtime error Improves reliability Compile error Dr. Clincy - Lecture
Generic ArrayList in JDK 1.5 Dr. Clincy - Lecture
Declaring Generic Classes Generic type E declared < > used getSize peek push pop isEmpty Following example creates a stack to hold strings and adds 3 strings to the stack GenericStack<String> stack1 = new GenericStack<>(); stack1.push(“CS1302”); stack1.push(“CS3503”); Stack1.push(“CS4622”); Dr. Clincy - Lecture
Raw Type and Backward Compatibility A generic class used WITHOUT specifying a concrete type (called a raw type) enables backward compatibility with earlier versions of Java. // raw type ArrayList list = new ArrayList(); This is roughly equivalent to ArrayList<Object> list = new ArrayList<Object>(); Dr. Clincy - Lecture
Wildcards To specify a range for a generic type, unbounded wildcards, bounded wildcards or lower bound wildcards can be used ? unbounded wildcard ? extends T bounded wildcard ? super T lower bound wildcard Same as ? Extends Object represents T or a subtype of T denotes T or a supertype of T – recall the supertype comes from the superclass Dr. Clincy - Lecture
Erasure and Restrictions on Generics Generics are implemented using an approach called type erasure. The compiler uses the generic type information to compile the code, but erases it afterwards. So the generic information is not available at run time. This approach enables the generic code to be backward-compatible with the legacy code that uses raw types. Dr. Clincy - Lecture
Restrictions on Generics Restriction 1: Cannot Create an Instance of a Generic Type. Restriction 2: Generic Array Creation is Not Allowed. Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. Restriction 4: Exception Classes Cannot be Generic. Dr. Clincy - Lecture