170 likes | 185 Views
Learn how generics are implemented in Java, their benefits in terms of error detection at compile time, and how to use the ArrayList class for storing objects of different types.
E N D
Example – How is it implemented ? public class GeometricObject { . . . Subclass Superclass public class Circle extendsGeometricObject { . . public class Rectangle extendsGeometricObject { . . The keyword extends tells the compiler that the subclass extends the superclass, thus, the subclass inherits the superclass’ methods
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 3
Motivations Moving from a subclass back up to a superclass, the classes become more general and less specific SuperClass Classes become more specific and concrete with each new subclass 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 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 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
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
Generic Type Old Way (prior to JDK 1.5) 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 cities = new ArrayList (); ArrayList<String> cities = new ArrayList<String>(); Either syntax will work ArrayList<String> cities = new ArrayList<>();
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.
What is 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.
Generic Type Generic Instantiation Runtime error Improves reliability Compile error
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”);
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>();
Wildcards To specify a range for a generic type, unbounded wildcards, bounded wildcards or lower bound wildcards can be used Same as ? Extends Object ? unbounded wildcard ? extends T bounded wildcard ? super T lower bound wildcard represents T or a subtype of T denotes T or a supertype of T – recall the supertype comes from the superclass
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.
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.