Peyman Dodangeh Sharif University of Technology Spring 2014.

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generics and The ArrayList Class
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
Java Generics.
Stacks. What is a stack? Last-in first-out data structure (LIFO) New objects are placed on top Removal restricted to top object Examples?
 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.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
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.
 2006 Pearson Education, Inc. All rights reserved Generics.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Java 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.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
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.
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.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
CIS 270—Application Development II Chapter 18-Generics.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
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:
Peyman Dodangeh Sharif University of Technology Fall 2014.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
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.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Sections 3.4 Formal Specification
Advanced Programming in Java
Advanced Programming in Java
Generic(Parameterized ) Types
Chapter 20 Generic Classes and Methods
Generics, Lambdas, Reflections
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Generic programming in Java
Advanced Programming in Java
Generics, Lambdas, Reflections
Generic Classes and Methods
Presentation transcript:

Peyman Dodangeh Sharif University of Technology Spring 2014

Agenda Generic Methods Generic Classes Generics and Inheritance Erasure Spring 2014Sharif University of Technology2

Spring 2014Sharif University of Technology3

Stack interfaces interface StringStack{ void push(String s); String pop(); } interface IntegerStack{ void push(Integer s); Integer pop(); } interface StudentStack{... Spring 2014Sharif University of Technology4

Sort Method static void sort(Integer[] array) { //... } static void sort(Double[] array) { //... } static void sort(String[] array) { //... } static void sort(Student[] array){ //... } Spring 2014Sharif University of Technology5

The Problem What is wrong with these examples? Code redundancy No effective code reuse Solution? Using Object class Pros and Cons? Compile-time type safety Spring 2014Sharif University of Technology6

The Solution Generic types and methods Methods with similar implementation Applicable for different parameters Spring 2014Sharif University of Technology7

Generic Methods Declaring a method which accepts different parameter types For each method invocation, the compiler searches the appropriate method If the compiler does not find a method, it looks for a compatible generic method Spring 2014Sharif University of Technology8 Type Parameter It says: In this method, E is not a regular type, it is a generic one

printArray() Generic Method Spring 2014Sharif University of Technology9

Benefits of Generics public static void printArray( E[] inputArray ){…} Restricting possible types Compile-time type checking printArray(stringArray) brings Compiler Error or exception? Spring 2014Sharif University of Technology10

Type parameter as the Return Type Spring 2014Sharif University of Technology11

Stack Generic Interface interface Stack { void push(T s); T pop(); } Stack stringStack = new... stringStack.push(“salam”); String s = stringStack.pop(); Spring 2014Sharif University of Technology12

public class Stack { private E[] elements ; private final int size; // number of elements in the stack private int top; // location of the top element public void push(E pushValue) { if (top == size - 1) // if stack is full throw new FullStackException(); elements[++top] = pushValue; } public E pop() { if (top == -1) // if stack is empty throw new EmptyStackException(); return elements[top--]; } public Stack() { size = 10; top = -1; elements = (E[]) new Object[size]; } Spring 2014Sharif University of Technology13 A note, later….

Using Stack Class Stack stack1 = new Stack (); stack1.push("first"); stack1.push("second"); System.out.println(stack1.pop()); Stack stack2 = new Stack (); stack2.push(1); stack2.push(2); System.out.println(stack2.pop()); Spring 2014Sharif University of Technology14

Compile-time Type Checking Stack stack1 = new Stack (); stack1.push(new Integer(2)); Compile-time error Spring 2014Sharif University of Technology15

public class Stack { private E[] elements ; private final int size; // number of elements in the stack private int top; // location of the top element public void push(E pushValue) { if (top == size - 1) // if stack is full throw new FullStackException(); elements[++top] = pushValue; } public E pop() { if (top == -1) // if stack is empty throw new EmptyStackException(); return elements[top--]; } public Stack() { size = 10; top = -1; elements = (E[]) new Student[size]; } Spring 2014Sharif University of Technology16 A note, later….

Raw Types Generic classes and methods can be used without type parameter Stack s = new Stack (); String as type parameter s.push(“salam”); s.push(new Integer(12));  Compiler Error Stack objectStack = new Stack(); no type parameter s.push(“salam”); s.push(new Integer(12)); s.push(new Student(“Ali Alavi”)); Spring 2014Sharif University of Technology17

No Generics in Runtime Generics is a compile-time aspect In runtime, there is no generic information All generic classes and methods are translated with raw types Byte code has no information about generics Only raw types in byte code This mechanism is named erasure Spring 2014Sharif University of Technology18

Erasure When the compiler translates generic method into Java bytecodes It removes the type parameter section It replaces the type parameters with actual types. This process is known as erasure Spring 2014Sharif University of Technology19

Erasure Example (1) class Stack { void push(T s){...} T pop() {...} } Is translated to class Stack { void push(Object s){...} Object pop() {...} } Spring 2014Sharif University of Technology20

Erasure Example (2) Translated to Spring 2014Sharif University of Technology21

What Happens if… public static void f(E i){ } public static void f(Number i){ } Compiler Error : Method f(Number) has the same erasure f(Number) as another method in this type Spring 2014Sharif University of Technology22

Generics and Inheritance A non-generic class can be inherited by a non-generic class As we saw before learning generics A generic class can be inherited from a non-generic class Adding generality to classes A non-generic class can be inherited from a generic class Removing generality A generic class can be inherited by a generic class Spring 2014Sharif University of Technology23

class GenericList extends Object{ public void add(T t){...} public T get(int i) {...} public void remove(int i) {...} } class GenericNumericList extends GenericList { } class NonZeroIntegerList extends GenericList { public void add(Integer t) { if(t==null || t==0) throw new RuntimeException(“Bad value"); super.add(t); } Spring 2014Sharif University of Technology24

Some Notes We can also create generic interfaces interface Stack { void push(T s); T pop(); } No primitives as type parameters Spring 2014Sharif University of Technology25

Multiple Type Parameters class MultipleType { private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } public void doSomthing(K k, T t){…} } MultipleType multiple = new MultipleType (); multiple.doSomthing(5, "123"); Spring 2014Sharif University of Technology26

Note You can not instantiate generic classes class Stack { T ref = new T(); } Syntax Error: Cannot instantiate the type T Why? Spring 2014Sharif University of Technology27

Note (2) You can not instantiate generic classes class Stack { T[] elements = new T[size]; } Syntax Error: Cannot instantiate the type T Why? Spring 2014Sharif University of Technology28

Note (3) You cannot create a generic array class Box { final T x; Box(T x) { this.x = x; } } Then, this line brings a compile error: Box [] bsa = new Box [3]; Why? Spring 2014Sharif University of Technology29 Syntax Error: Cannot create a generic array of Box Syntax Error: Cannot create a generic array of Box

Reason Operations such as instanceof and new are runtime operations They use a type at runtime With erasure type information is removed at runtime So these operations are Meaningless Although, they may be possible Spring 2014Sharif University of Technology30 T ref = new T();  impossible which constructor? T[] elements = new T[size ];  Meaningless Box [] bsa = new Box [3];  Meaningless

Generics and Java 7 Older versions: ArrayList list = new ArrayList (); With Java 7: ArrayList list = new ArrayList<>(); Type information after new are ignored. List >> list = new ArrayList<>(); Spring 2014Sharif University of Technology31

Further Reading Wildcards as type parameters Java generics vs. C++ templates Erasure is different in these languages Type Argument inference More on erasure TIJ is so better than Deitel in generics chapter More Depth Spring 2014Sharif University of Technology32

Quiz! Spring 2014Sharif University of Technology33

Quiz Write a generic equals() and toString() methods Use Pair class for at lPair class which can hold two objects Override appropriate east two different type-sets The pair is ordered Two ordered pairs are equal if their corresponding elements are equal Spring 2014Sharif University of Technology34

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } class B extends A{ public Object f(Object o){ return new String("salam"); } B.f() overrides A.f() Spring 2014Sharif University of Technology35

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } class B extends A{ public String f(Object o){ return new String("salam"); } B.f() overrides A.f() Spring 2014Sharif University of Technology36

A Note on Inheritance class A{ public Object f(Object o){ return new Object(); } } class B extends A{ public Object f(String o){ return new String("salam"); } } B.f() is overloading A.f() B.f() does not override A.f() Spring 2014Sharif University of Technology37

Pair class (Quiz) Pair equals toString Spring 2014Sharif University of Technology38

class Pair { private T first; private K second; public Pair(T t, K k) { this.first = t; this.second = k; } public T getFirst() { return first; } public K getSecond() { return second; } public String toString() { return "[" + second + ", " + first + "]"; } Spring 2014Sharif University of Technology39

Pair pair1 = new Pair (4, "Ali"); Integer i = pair1.getFirst(); String s = pair1.getSecond(); Pair pair2 = new Pair ("salam", true); String ss = pair2.getFirst(); Boolean bb = pair2.getSecond(); Spring 2014Sharif University of Technology40

equals() method public boolean equals(Pair pair) { return pair.first.equals(first) && pair.second.equals(second); } What is wrong with this implementation? Spring 2014Sharif University of Technology41

boolean equals(Pair pair) It should check for nullity of pair It should check for nullity of pair.first and pair.second It should check for nullity of this.first and this.second This method does not override equals() It is overloading it Correct signature: boolean equals(Object pair) What if parameter is not a Pair? Spring 2014Sharif University of Technology42

Type Checking public boolean equals(Object o) { Pair pair = null; try{ pair = (Pair ) o; }catch(ClassCastException e){ return false; } return pair.first.equals(first) && pair.second.equals(second); } Spring 2014Sharif University of Technology43

Spring 2014Sharif University of Technology44

Spring 2014Sharif University of Technology45