Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.

Slides:



Advertisements
Similar presentations
Generic programming in Java
Advertisements

C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Java Generics.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
 2005 Pearson Education, Inc. All rights reserved Generics.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
3C-1 Purity Typing Language semantics Inheritance model  Single vs. Multiple inheritance  Common root Modular mechanisms Generics Object Oriented Languages.
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Object-oriented Programming in Java
Chapter 20 Generic Classes and Methods
CMSC 202 Static Methods.
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Classes and Objects Static Methods
CSC 220 – Processing Spring, 2017
Java Programming Language
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Java Generics

2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class is a subclass of java.lang.Object  So there's always at least one common superclass Collections were actually collections of objects  You can put anything into a collection  When you extract something, its static type is Object

3 Java 5 and Beyond Parametric polymorphism introduced in Java 5  September 2004  Most significant enhancement since Java's birth May resemble C++ templates, but:  Implemented differently  “Compile once and for all”  Better error messages  Type constraints are explicit  Less power (e.g., cannot inherit from a type parameter)‏  Parameters can only be types  No executable blowup

4 Generics – Before and After // Without generics List list = new ArrayList(); list.add(new Integer(0)); Integer x = (Integer) list.get(0); // Programmer must downcast list.add("abc"); Integer y = (Integer) list.get(1); // Run -time exception // With Generics – The compiler “knows” the type of the list elements List list = new ArrayList (); list.add(new Integer(0)); Integer x = list.get(0); list.add("abc"); // Compiler Error – Expected ineteger

5 A Generic Method public static List dup(T t, int n) { List result = new ArrayList (); for(int i = 0; i < n; ++i)‏ result.add(t); return result; }... List list = dup("abc", 2); // Implicit instantiation // Explicit not supported...

6 Recap: java.lang.Integer, Number package java.lang; public abstract class Number { public abstract int intValue(); public abstract long longValue(); public abstract float floatValue(); public abstract double doubleValue(); public byte byteValue() { return (byte) intValue(); } public short shortValue() { return (short) intValue(); } } package java.lang; public final class Integer extends Number { private final int n; public Integer(int v) { n = v; } public int intValue() { return n; } public long longValue() { return (long) n; } public float floatValue() { return (float) n; } public double doubleValue() { return (double) n; } }

7 The Cell class public class Cell { private T value; public T get() { return value; } public void set(T t) { value = t; } // T is at least an Object, so it supports toString() ‏ public String toString() { return value.toString(); } }

8 Using Cell Using Cell static void main(String[] args) { Cell ci = new Cell (); ci.set(new Integer(5)); System.out.println(ci.get()); int n = ci.get(); // auto-unboxing n = n*n; ci.set(n); // auto-boxing System.out.println(ci.get()); Cell cn = new Cell (); cn.set(ci.get()); }

9 Type Parameters with Upper Bounds public class NumberCell { private T value; public T get() { return value; } public void set(T t) { value = t; } public String toString() { return value.toString(); } // T is at least a Number, so it supports intValue() ‏ public int sum(int x) { return value.intValue() + x; } } The extend keyword specifies an upper bound for T  Can be used with both classes and interfaces Can have multiple bounds:  T extends MyClass & MyInterface

10 Cell is not compatible with Cell Cell is not compatible with Cell static void assign(Cell co, Object o) { co.set(o); } void main() { Cell ci = new Cell (); assign(ci, new Integer(10)); // Compiler error: // Cannot convert from Cell to Cell // Otherwise, the following code would break at run time assign(ci, "abc"); Integer n = ci.get(); System.out.println(n.intValue()); } The same conformance issue as with covariant input arguments

11 A better version of assign() static void assign(Cell co, T o) { co.set(o); } void main() { Cell ci = new Cell (); assign(ci, new Integer(10)); // Now it works }

12 The Wildcard: The Wildcard: static > boolean isNullA(C c) { T t = c.get(); return t == null; } static > boolean isNullB(C c) { return c.get() == null; } static boolean isNullC(Cell c) { return c.get() == null; } If a type parameter is used exactly once – and this occurrence is inside an upper bound – it can be replaced with a wildcard If a type parameter is used exactly once – and this occurrence is as a type of formal parameter of the method – it can be replaced with its upper bound

13 Wildcard: Type Checking Rules static boolean isNullC(Cell c) {... } Inside isNullC() :  ? Cannot be used to declare the type of a variable  c.get() return an Object  c.set(o) is not allowed, even if o is of type Object. Exception to this rule: c.set(null) is allowed For every type Y, the type X is a supertype of X

14 Lower Bounds public static class Cell { private T value; public T get() { return value; } public void set(T t) { value = t; } public void copyTo(Cell c) { c.set(value); } } The super keyword specifies a lower bound for a wild-card  Cannot be used with regular type parameters

15 Implementation of Generics: Type Erasure Compiling a Generic class: Cell  Check: Type correctness  Erase: Replace T with its upper bound ( Object )‏  Compile: to byte code Compiling an instantiation: Cell c;  Replace: The instantiated type with the raw type  Annotate: add a “footnote” specifying the substitution: c: T = String The annotation is saved in the class file declaring c Compiling a field access or a message send: c.get()‏  Obtain: The annotation of the receiver variable, c  Check: Actual method parameters against the actual type parameters (None in this example)‏  Downcast: insert a cast of the return type to the actual type parameter, String

16 Type Erasure Benefit of Erasure:  Binary compatibility with older libraries: List is translated to type List (raw type )‏ Code compiled using a "pre-generics" class works correctly Code written using a "pre-generics" class still compiles and work Drawback of Erasure  generic type information is not known at runtime List and List refer to List  type variables cannot be used in new expressions Type is unknown at runtime

17 Type Erasure: Example Generic form class Foo { T m(Set s) { } } Erased form: class Foo { Number m(Set s){} }

18 Erasure: Loophole List list = new ArrayList (); Object o = list; List err = (List ) o; // Warning: Unchecked Conversion err.add("abc"); Integer i = list.get(0); // Runtime error: cast from String to Integer Unchecked conversion warning  Issued by the compiler when we use an instantiated type in a position where only the raw type is available  Usually appears when we cast to an instantiated generic type The downcast check will be partial  Indicates a danger of type errors at run time  Avoid at all costs