Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generic Java 21/2-2003. What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.

Similar presentations


Presentation on theme: "Generic Java 21/2-2003. What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the."— Presentation transcript:

1 Generic Java 21/2-2003

2 What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the declaration This makes it possible to write generic functions that will work with many different types Analogous to parametric types

3 Java: The current situation Utility classes with simulated generics Ex. a container such as a Collection where all elements are treated as instances of type Object, regardless of their original types While retrieving the elements it is necessary to cast them to their original types This is inconvenient and error-prone

4 Motivation for GJ avoid having to write casts make it possible to catch cast errors at compile-time should be compatible with the unextended java language

5 Assigning type parameters in GJ class Pair { private A element1; private B element2; public Pair (A element1, B element2) { this.element1 = element1; this.element2 = element2; } public A getElement1() { return element1; } public B getElement2() { return element2; } class Test { public static void main (String[] args) { Pair shoe; shoe = new Pair (”Addidas”, new Integer (”38”)); String name = shoe.getElement1(); Integer size = shoe.getElement2(); }

6 Assigning it is not possible to assign an object to another object of the same type, but with a different type parameter it will, for example, cause a compile error if you try to assign Pair to Pair

7 Invariant subtyping Not allowed: Collection c = new Collection (); Allowed: Collection = new LinkedList ();

8 Translating GJ the translation erases the type parameters, maps type variables to their bounds, inserts the appropriate casts, and bridge methods the GJ-compiler translates the parameterized source code to get the generic effect with features already present in Java (but in a type-safe manner) the translation is homogeneous the type parameters are not available run-time

9 Consistency with legacy code translates into normal-looking Java code raw types retrofitting unchecked warnings


Download ppt "Generic Java 21/2-2003. What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the."

Similar presentations


Ads by Google