 2005 Pearson Education, Inc. All rights reserved. 1 18 Generics.

Slides:



Advertisements
Similar presentations
Generics and the ArrayList Class
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Generic programming in Java
 2005 Pearson Education, Inc. All rights reserved Introduction.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
 2006 Pearson Education, Inc. All rights reserved Generics.
©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.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Java Generics.
INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Introduction to Generics
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CIS 270—Application Development II Chapter 18-Generics.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
 2005 Pearson Education, Inc. All rights reserved Arrays.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
 2006 Pearson Education, Inc. All rights reserved Templates.
(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.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Chapter 18 Introduction to Custom Templates
Chapter 20 Generic Classes and Methods
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Continuing Chapter 11 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Chapter 9 Object-Oriented Programming: Inheritance
Chapter 6 Methods: A Deeper Look
Chapter 19 Generics.
Generic Classes and Methods
Presentation transcript:

 2005 Pearson Education, Inc. All rights reserved Generics

 2005 Pearson Education Inc. All rights reserved. 2 Every man of genius sees the world at a different angle from his fellows. — Havelock Ellis …our special individuality, as distinguished from our generic humanity. — Oliver Wendell Holmes, Sr. Born under one law, to another bound. — Lord Brooke You deal in the raw material of opinion, and, if my convictions have any validity, opinion ultimately governs the world. — Woodrow Wilson

 2005 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn:  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack class that can be used to store objects of any class or interface type.  To understand how to overload generic methods with non-generic methods or with other generic methods.  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information about a parameter is not required in the method body.  The relationship between generics and inheritance.

 2005 Pearson Education, Inc. All rights reserved Introduction 18.2 Motivation for Generic Methods 18.3 Generic Methods: Implementation and Compile-Time Translation 18.4 Additional Compile-Time Translation Issues: 18.5 Overloading Generic Methods 18.6 Generic Classes 18.7 Raw Types 18.8 Wildcards in Methods That Accept Type Parameters 18.9 Generics and Inheritance: Notes Wrap-Up Internet and Web Resources

 2005 Pearson Education, Inc. All rights reserved Introduction Generics – New feature of J2SE 5.0 – Provide compile-time type safety Catch invalid types at compile time – Generic methods A single method declaration A set of related methods – Generic classes A single class declaration A set of related clases

 2005 Pearson Education, Inc. All rights reserved. 6 Software Engineering Observation 18.1 Generic methods and classes are among Java’s most powerful capabilities for software reuse with compile-time type safety.

 2005 Pearson Education, Inc. All rights reserved Motivation for Generic Methods Overloaded methods – Perform similar operations on different types of data – Overloaded printArray methods Integer array Double array Character array – Only reference types can be used with generic methods and classes

 2005 Pearson Education, Inc. All rights reserved. 8 Outline OverloadedMethods.java (1 of 3) Line 7 Line 17 Method printArray accepts an array of Integer objects Method printArray accepts an array of Double objects

 2005 Pearson Education, Inc. All rights reserved. 9 Outline OverloadedMethods.java (2 of 3) Line 27 Method printArray accepts an array of Character objects

 2005 Pearson Education, Inc. All rights reserved. 10 Outline OverloadedMethods.java (3 of 3) Line 44 Line 46 Line 48 Program output At compile time, the compiler determines argument integerArray ’s type (i.e., Integer []), attempts to locate a method named printArray that specifies a single Integer [] parameter (lines 7-14) At compile time, the compiler determines argument doubleArray ’s type (i.e., Double []), attempts to locate a method named printArray that specifies a single Double [] parameter (lines 17-24) At compile time, the compiler determines argument characterArray ’s type (i.e., Character []), attempts to locate a method named printArray that specifies a single Character [] parameter (lines 7-14)

 2005 Pearson Education, Inc. All rights reserved Motivation for Generic Methods (Cont.) Study each printArray method – Array element type appears in two location Method header for statement header Combine three printArray methods into one – Replace the element types with a generic name E – Declare one printArray method Display the string representation of the elements of any array

 2005 Pearson Education, Inc. All rights reserved. 12 Outline Fig | printArray method in which actual type names are replaced by convention with the generic name E. Replace the element type with a single generic type E

 2005 Pearson Education, Inc. All rights reserved Generic Methods: Implementation and Compile-Time Translation Reimplement Fig using a generic method – Method calls are identical – Outputs are identical Generic method declaration – Type parameter section Delimited by angle brackets ( ) Precede the method’s return type Contain one or more type parameters – Also called formal type paramters

 2005 Pearson Education, Inc. All rights reserved Generic Methods: Implementation and Compile-Time Translation Type parameter – Also known as type variable – An identifier that specifies a generic type name – Used to declare return type, parameter types and local variable types – Act as placeholders for the types of the argument passed to the generic method Actual type arguments – Can be declared only once but can appear more than once public static void printTwoArrays( E[] array1, E[] array2 )

 2005 Pearson Education, Inc. All rights reserved. 15 Common Programming Error 18.1 When declaring a generic method, failing to place a type parameter section before the return type of a method is a syntax error—the compiler will not understand the type parameter name when it is encountered in the method.

 2005 Pearson Education, Inc. All rights reserved. 16 Outline GenericMethodTest.java (1 of 2) Line 7 Lines 10 Type parameter section delimited by angle brackets ( ) Use the type parameter to declare method printArray ’s parameter type Use the type parameter to declare method printArray ’s local variable type

 2005 Pearson Education, Inc. All rights reserved. 17 Outline GenericMethodTest.java (2 of 2) Line 24 Line 26 Line 28 Program output Invoke generic method printArray with an Integer array Invoke generic method printArray with a Double array Invoke generic method printArray with a Character array

 2005 Pearson Education, Inc. All rights reserved. 18 Good Programming Practice 18.1 It is recommended that type parameters be specified as individual capital letters. Typically, a type parameter that represents the type of an element in an array (or other collection) is named E for “element.”

 2005 Pearson Education, Inc. All rights reserved. 19 Common Programming Error 18.2 If the compiler cannot match a method call to a non-generic or a generic method declaration, a compilation error occurs.

 2005 Pearson Education, Inc. All rights reserved. 20 Common Programming Error 18.3 If the compiler does not find a method declaration that matches a method call exactly, but does find two or more generic methods that can satisfy the method call, a compilation error occurs.

 2005 Pearson Education, Inc. All rights reserved Generic Methods: Implementation and Compile-Time Translation (Cont.) Compile-time translation – Erasure Remove type parameter section Replace type parameters with actual types Default type is Object

 2005 Pearson Education, Inc. All rights reserved. 22 Outline Fig | Generic method printArray after erasure is performed by the compiler. Remove type parameter section and replace type parameter with actual type Object Replace type parameter with actual type Object

 2005 Pearson Education, Inc. All rights reserved Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type Application of Fig – Generic method – Use Type parameters in the return type and parameter list Generic interface – Specify, with a single interface declaration, a set of related types – E.g., Comparable Method integer1.compareTo( integer2 ) – Compare two objects of the same class – Return 0 if two objects are equal – Return -1 if integer1 is less than integer2 – Return 1 if integer1 is greater than integer2

 2005 Pearson Education, Inc. All rights reserved. 24 Outline MaximumTest.java (1 of 2) Line 7 Line 9 Line Lines Type parameter section specifies that only object of classes that implement interface Comparable can be used with this method Type parameter is used in the return type of method maximum Invokes method compareTo method Comparable to compare y and max Invokes method compareTo method Comparable to compare z and max Assign x to local variable max

 2005 Pearson Education, Inc. All rights reserved. 25 Outline MaximumTest.java (2 of 2) Line 23 Line 25 Line 27 Program output Invoke generic method maximum with three integers Invoke generic method maximum with three doubles Invoke generic method maximum with three strings

 2005 Pearson Education, Inc. All rights reserved Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type (Cont.) Upper bound of type parameter – Default is Object – Always use keyword extends E.g., T extends Comparable – When compiler translates generic method to Java bytecode Replaces type parameter with its upper bound Insert explicit cast operation e.g., line 23 of Fig I preceded by an Integer cast (Integer) maximum( 3, 4, 5 )

 2005 Pearson Education, Inc. All rights reserved. 27 Outline Erasure replaces type parameter T with its upper bound Comparable

 2005 Pearson Education, Inc. All rights reserved Overloading Generic Method Generic method may be overloaded – By another generic method Same method name but different method parameters – By non-generic methods Same method name and number of parameters When compiler encounters a method call – Search for most precise matching method first Exact method name and argument types – Then search for inexact but applicable matching method

 2005 Pearson Education, Inc. All rights reserved Generic Classes Generic classes – Use a simple, concise notation to indicate the actual type(s) – At compilation time, Java compiler ensures the type safety uses the erasure technique to enable client code to interact with the generic class Parameterized classes – Also called parameterized types – E.g., Stack

 2005 Pearson Education, Inc. All rights reserved Generic Classes (Cont.) Generic class declaration – Looks like a non-generic class declaration – Except class name is followed by a type parameter section The –Xlint:unchecked option – Compiler cannot 100% ensure type safety

 2005 Pearson Education, Inc. All rights reserved. 31 Outline Stack.java (1 of 2) Line 4 Line 8 Line 22 Generic class declaration, class name is followed by a type parameter section Declare elements as an array that stores objects of type E Create an array of type E. The generic mechanism does not allow type parameter in array-creation expressions because the type parameter is not available at runtime

 2005 Pearson Education, Inc. All rights reserved. 32 Outline Stack.java (2 of 2) Lines Lines Method push pushes element of type E onto stack Method pop returns the top element, which is of type E

 2005 Pearson Education, Inc. All rights reserved. 33 Outline FullStack Exception.java

 2005 Pearson Education, Inc. All rights reserved. 34 Outline EmptyStack Exception.java

 2005 Pearson Education, Inc. All rights reserved Generic Classes (Cont.) Generic class at compilation time – Compiler performs erasure on class’s type parameters – Compiler replaces type parameters with their upper bound Generic class test program at compilation time – Compiler performs type checking – Compiler inserts cast operations as necessary

 2005 Pearson Education, Inc. All rights reserved. 36 Outline StackTest.java (1 of 6) Line 9 Line 10 Lines Generic class Stack ’s type argument is Double Generic class Stack ’s type argument is Integer Instantiate object doubleStack of size 5 and ingeterStack of size 10

 2005 Pearson Education, Inc. All rights reserved. 37 Outline StackTest.java (2 of 6) Line 36 Invoke Stack ’s method push to place a double value onto doubleStack

 2005 Pearson Education, Inc. All rights reserved. 38 Outline StackTest.java (3 of 6) Line 58 Auto-unboxing occurs when the value returned by pop ( Double ) is assigned to a double primitive variable

 2005 Pearson Education, Inc. All rights reserved. 39 Outline StackTest.java (4 of 6) Line 81 Invoke Stack ’s method push to place an int value onto integerStack

 2005 Pearson Education, Inc. All rights reserved. 40 Outline StackTest.java (5 of 6) Line 103 Auto-unboxing occurs when the value returned by pop ( Integer ) is assigned to an int primitive variable

 2005 Pearson Education, Inc. All rights reserved. 41 Outline StackTest.java (6 of 6) Program output

 2005 Pearson Education, Inc. All rights reserved Generic Classes (Cont.) Creating generic methods to test class Stack – Method testPush Perform same tasks as testPushDouble and testPushInteger – Method testPop Perform same tasks as testPopDouble and testPopInteger

 2005 Pearson Education, Inc. All rights reserved. 43 Outline StackTest2.java (1 of 4) Lines Invoke generic methods testPush and testPop to push elements onto stack and pop elements from stack

 2005 Pearson Education, Inc. All rights reserved. 44 Outline StackTest2.java (2 of 4) Lines Line 35 Generic method testPush replaces testPushDouble and testPushInteger Replace element type Double/Integer with type parameter T

 2005 Pearson Education, Inc. All rights reserved. 45 Outline StackTest2.java (3 of 4) Lines Line 55 Generic method testPop replaces testPopDouble and testPopInteger Replace element type Double/Integer with type parameter T

 2005 Pearson Education, Inc. All rights reserved. 46 Outline StackTest2.java (4 of 4) Program output

 2005 Pearson Education, Inc. All rights reserved Raw Types Raw type – Enables to instantiate generic class without specifying a type argument e.g., Stack objectStack = new Stack( 5 ); objectStack is said to have a raw type – Important for backwards compatibility with prior versions – A raw type Stack variable can be assigned a Stack that specifies a type argument – A Stack variable that specifies a type argument can be assigned a raw type Stack Permitted but unsafe Use the –Xlint:unchecked option to compile

 2005 Pearson Education, Inc. All rights reserved. 48 Outline RawTypeTest.java (1 of 5) Line 14 Line 17 Line 20 Instantiate generic class Stack with raw type Assign a Stack to variable rawTypeStack2 Assign a Stack of raw type to Stack. Legal but unsafe

 2005 Pearson Education, Inc. All rights reserved. 49 Outline RawTypeTest.java (2 of 5)

 2005 Pearson Education, Inc. All rights reserved. 50 Outline RawTypeTest.java (3 of 5)

 2005 Pearson Education, Inc. All rights reserved. 51 Outline RawTypeTest.java (4 of 5) Program output

 2005 Pearson Education, Inc. All rights reserved. 52 Outline RawTypeTest.java (5 of 5) Program output

 2005 Pearson Education, Inc. All rights reserved. 53 Outline Fig | Warning message from the compiler.

 2005 Pearson Education, Inc. All rights reserved Wildcards in Methods That Accept Type Parameters Data structure ArrayList – Dynamically resizable, array-like data structure – Method add – Method toString Motivation for using wildcards – Implement a generic method sum Total the numbers in a collection Receive a parameter of type ArrayList Use method doubleValue of class Number to obtain the Number ’s underlying primitive value as a double value

 2005 Pearson Education, Inc. All rights reserved. 55 Outline TotalNumbers.java (1 of 2) Line 11 Line 12 Line 15 Line 19 Declare and initialize array numbers Declare and initialize numberList, which stores Number objects Add elements in numbers array to ArrayList numberList Invoke method sum to calculate the total of the elements stored in numberList

 2005 Pearson Education, Inc. All rights reserved. 56 Outline TotalNumbers.java (2 of 2) Line 23 Lines Program output Method sum accepts an ArrayList that stores Number objects Use method doubleValue of class Number to obtain the Number ’s underlying primitive value as a double value

 2005 Pearson Education, Inc. All rights reserved Wildcards in Methods That Accept Type Parameters (Cont.) Implementing method sum with a wildcard type argument in its parameter – Number is the superclass of Integer – ArrayList is not a supertype of ArrayList – Cannot pass ArrayList to method sum – Use wildcard to create a more flexible version of sum ArrayList ? Represents an “unknown type” Unknown type argument must be either Number or a subclass of Number Cannot use wildcard as a type name through method body

 2005 Pearson Education, Inc. All rights reserved. 58 Outline WildcardTest.java (1 of 3) Line 12 Line 20 Line 25 Declare and create ArrayList integerList to hold Integer s Invoke method sum to calculate the total of the elements stored in integerList Declare and create ArrayList doubleList to hold Double s

 2005 Pearson Education, Inc. All rights reserved. 59 Outline WildcardTest.java (2 of 3) Line 33 Line 38 Line 46 Line 50 Invoke method sum to calculate the total of the elements stored in doubleList Invoke method sum to calculate the total of the elements stored in numberList Declare and create ArrayList integerList to hold Numbers s The ArrayList argument’s element types are not directly known by the method, they are known to be at least of type Number

 2005 Pearson Education, Inc. All rights reserved. 60 Outline WildcardTest.java (3 of 3) Program output

 2005 Pearson Education, Inc. All rights reserved. 61 Common Programming Error 18.4 Using a wildcard in a method’s type parameter section or using a wildcard as an explicit type of a variable in the method body is a syntax error. occurs.

 2005 Pearson Education, Inc. All rights reserved Generics and Inheritance: Notes Inheritance in generics – Generic class can be derived from non-generic class e.g., class Object is superclass of every generic class – Generic class can be derived from another generic class e.g., Stack is a subclass of Vector – Non-generic class can be derived from generic class e.g., Properties is a subclass of Hashtable – Generic method in subclass can override generic method in superclass If both methods have the same signature