Advanced Programming Behnam Hatami Fall 2017.

Slides:



Advertisements
Similar presentations
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Advertisements

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.
Java Generics.
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 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.
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.
Chapter 3 Introduction to Collections – Stacks Modified
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CMSC 330: Organization of Programming Languages Java Generics.
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.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Java Generics And collections
Modern Programming Tools And Techniques-I
Sections 3.4 Formal Specification
Building Java Programs
CIS265/506 Cleveland State University – Prof. Victor Matos
Java Generics.
Generic(Parameterized ) Types
Chapter 20 Generic Classes and Methods
Exceptions, Interfaces & Generics
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Generics, Lambdas, Reflections
Continuing Chapter 11 Inheritance and Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
CS 302 Week 11 Jim Williams, PhD.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming Behnam Hatami Fall 2017.
Методика наставе рачунарства
Chapter 19 Generics Dr. Clincy - Lecture.
Advanced Programming in Java
Advanced Programming Behnam Hatami Fall 2017.
Building Java Programs
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Advanced Programming in Java
Type Safety, Generics, Lambdas, Class Object
ArrayLists 22-Feb-19.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
ArrayLists 27-Apr-19.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Generic Programming.
Generics 5/11/2019.
Chapter 21 Generics.
Chapter 19 Generics.
CMPE212 – Reminders Assignment 2 due next Friday.
Generic Classes and Methods
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Chapter 19 Generics.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Advanced Programming Behnam Hatami Fall 2017

Agenda Generic Methods Generic Classes Generics and Inheritance Erasure

Stack interfaces interface StringStack{ void push(String s); String pop(); } interface IntegerStack{ void push(Integer s); Integer pop(); interface StudentStack{...

Sort Method static void sort(Integer[] array) { // ... } static void sort(Double[] array) { static void sort(String[] array) { static void sort(Student[] array){

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

The Solution Generic types and methods Methods with similar implementation Applicable for different parameters

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 Type Parameter It says: In this method, E is not a regular type, it is a generic one

printArray() Generic Method

Benefits of Generics public static < E extends Number> void printArray( E[] inputArray ){…} Restricting possible types Compile-time type checking printArray(stringArray) brings Compiler Error or exception?

Type parameter as the Return Type

Stack Generic Interface interface Stack<T>{ void push(T s); T pop(); } Stack<String> stringStack = new ... stringStack.push(“salam”); String s = stringStack.pop();

public class Stack<E > { 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]; A note, later….

Using Stack Class Stack<String> stack1 = new Stack<String>(); stack1.push("first"); stack1.push("second"); System.out.println(stack1.pop()); Stack<Integer> stack2 = new Stack<Integer>(); stack2.push(1); stack2.push(2); System.out.println(stack2.pop());

Compile-time Type Checking Stack<String> stack1 = new Stack<String>(); stack1.push(new Integer(2)); Compile-time error

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

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

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

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

Erasure Example (1) Is translated to class Stack { class Stack<T>{ void push(T s){...} T pop() {...} } Is translated to class Stack { void push(Object s){...} Object pop() {...}

Erasure Example (2) Translated to

What Happens if… public static <E extends Number> 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

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

class GenericList<T> extends Object{ class NonZeroIntegerList public void add(T t){...} extends GenericList<Integer>{ public T get(int i) {...} public void add(Integer t) { public void remove(int i) {...} if(t==null || t==0) } throw new RuntimeException(“Bad value"); class GenericNumericList<T extends Number> super.add(t); extends GenericList<T>{

Some Notes We can also create generic interfaces interface Stack<T>{ void push(T s); T pop(); } No primitives as type parameters

Multiple Type Parameters class MultipleType<T,K>{ private T t; public T getT() { MultipleType<String, Integer> multiple = return t; new MultipleType<String, Integer>(); } public void setT(T t) { multiple.doSomthing(5, "123"); this.t = t; public void doSomthing(K k, T t){…}

Note class Stack<T>{ T ref = new T(); } You can not instantiate generic classes class Stack<T>{ T ref = new T(); } Syntax Error: Cannot instantiate the type T Why?

Note (2) class Stack<T>{ T[] elements = new T[size]; } You can not instantiate generic classes class Stack<T>{ T[] elements = new T[size]; } Syntax Error: Cannot instantiate the type T Why?

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

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 T ref = new T();  impossible which constructor? T[] elements = new T[size];  Meaningless Box<String>[] bsa = new Box<String>[3];  Meaningless

Generics and Java 7 Older versions: With Java 7: ArrayList<String> list = new ArrayList<String>(); With Java 7: ArrayList<String> list = new ArrayList<>(); Type information after new are ignored. List<Map<Long, Set<Integer>>> list = new ArrayList<>();

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

Wow!!! public static void wow(ArrayList<String> list) { public static void main(String args[]) { Method method = list.getClass().getMethod("add", Object.class); ArrayList<String> s = new ArrayList<String>(); wow(s); method.invoke(list, new Integer(2)); for (Object string : s) { System.out.println(string); }

A Note on Inheritance B.f() overrides A.f() class A{ class B extends A{ public Object f(Object o){ return new Object(); return new String("salam"); } B.f() overrides A.f()

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()

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

Pair class (Quiz) Pair<T, K> equals toString

class Pair<T,K>{ 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 + "]";

Pair<Integer, String> pair1 = new Pair<Integer, String>(4, "Ali"); Integer i = pair1.getFirst(); String s = pair1.getSecond(); Pair<String, Boolean> pair2 = new Pair<String, Boolean>("salam", true); String ss = pair2.getFirst(); Boolean bb = pair2.getSecond();

equals() method public boolean equals(Pair<T,K> pair) { return pair.first.equals(first) && pair.second.equals(second); } What is wrong with this implementation?

boolean equals(Pair<T,K> 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?

Type Checking public boolean equals(Object o) { Pair<T, K> pair = null; try{ pair = (Pair<T, K>) o; }catch(ClassCastException e){ return false; } return pair.first.equals(first) && pair.second.equals(second);

References Java How to Program (9th Edition) Deitel & Deitel Thinking in Java (Fourth Edition) Bruce Eckel Java cup

Any Question