Advanced Programming in Java
Advanced Programming in JavaPeyman DodangehSharif University of TechnologySpring 2014AgendaGeneric MethodsGeneric ClassesGenerics and InheritanceErasure
Spring 2014Sharif University of Technology2Spring 2014Sharif University of Technology3
Stack interfacesinterface StringStack{void push(String s);String pop();}interface IntegerStack{void push(Integer s);Integer pop();}interface StudentStack{...Spring 2014Sharif University of Technology4Sort Methodstatic void sort(Integer[] array) {// ...}
static void sort(Double[] array) {// ...}static void sort(String[] array) {// ...}static void sort(Student[] array){// ...}
Spring 2014Sharif University of Technology5The ProblemWhat is wrong with these examples?Code redundancy No effective code reuseSolution?Using Object classPros and Cons?Compile-time type safety
Spring 2014Sharif University of Technology6The SolutionGeneric types and methodsMethods with similar implementationApplicable for different parametersSpring 2014Sharif University of Technology7Generic MethodsDeclaring a method which accepts different parameter types
For each method invocation, the compiler searches the appropriate methodIf the compiler does not find a method, it looks for a compatible generic method
Spring 2014Sharif University of Technology8
Type ParameterIt says: In this method, E is not a regular type, it is a generic oneprintArray() Generic MethodSpring 2014Sharif University of Technology9
Benefits of Genericspublic static < E extends Number> void printArray( E[] inputArray ){}
Restricting possible typesCompile-time type checking
printArray(stringArray) bringsCompiler Erroror exception?Spring 2014Sharif University of Technology10Type parameter as the Return TypeSpring 2014Sharif University of Technology11
Stack Generic Interfaceinterface Stack{void push(T s);T pop();}
Stack stringStack = new ...stringStack.push(salam);String s = stringStack.pop();Spring 2014Sharif University of Technology12public class Stack {private E[] elements ;private final int size; // number of elements in the stackprivate int top; // location of the top elementpublic 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 emptythrow new EmptyStackException();return elements[top--]; }public Stack() {size = 10; top = -1; elements = (E[]) new Object[size]; }}Spring 2014Sharif University of Technology13A note, later.Using Stack Class Stack stack1 = new Stack();stack1.push("first");stack1.push("second");System.out.println(stack1.pop());System.out.println(stack1.pop());
Stack stack2 = new Stack();stack2.push(1);stack2.push(2);System.out.println(stack2.pop());System.out.println(stack2.pop());Spring 2014Sharif University of Technology14Compile-time Type CheckingStack stack1 = new Stack();stack1.push(new Integer(2));
Compile-time error
Spring 2014Sharif University of Technology15public class Stack {private E[] elements ;private final int size; // number of elements in the stackprivate 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 emptythrow new EmptyStackException();return elements[top--]; }public Stack() {size = 10; top = -1; elements = (E[]) new Student[size]; }}Spring 2014Sharif University of Technology16A note, later.Raw TypesGeneric classes and methods can be used without type parameterStack s = new Stack(); String as type parameters.push(salam);s.push(new Integer(12)); Compiler ErrorStack objectStack = new Stack(); no type parameters.push(salam);s.push(new Integer(12));s.push(new Student(Ali Alavi));
Spring 2014Sharif University of Technology17No Generics in RuntimeGenerics is a compile-time aspectIn runtime, there is no generic informationAll generic classes and methods are translated with raw typesByte code has no information about genericsOnly raw types in byte codeThis mechanism is named erasureSpring 2014Sharif University of Technology18ErasureWhen the compiler translates generic method into Java bytecodesIt removes the type parameter section It replaces the type parameters with actual types.This process is known as erasureSpring 2014Sharif University of Technology19Erasure 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 Technology20Erasure Example (2)Translated to
Spring 2014Sharif University of Technology21
What Happens ifpublic 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 typeSpring 2014Sharif University of Technology22Generics and InheritanceA non-generic class can be inherited by a non-generic classAs we saw before learning generics
A generic class can be inherited from a non-generic classAdding generality to classes
A non-generic class can be inherited from a generic classRemoving generality
A generic class can be inherited by a generic class
Spring 2014Sharif University of Technology23class 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 Technology24Some NotesWe can also create generic interfacesinterface Stack{void push(T s);T pop();}
No primitives as type parameters
Spring 2014Sharif University of Technology25Multiple Type Parametersclass 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 Technology26NoteYou can not instantiate generic classesclass Stack{T ref = new T();}Syntax Error: Cannot instantiate the type TWhy?Spring 2014Sharif University of Technology27Note (2)You can not instantiate generic classesclass Stack{T[] elements = new T[size];}Syntax Error: Cannot instantiate the type TWhy?Spring 2014Sharif University of Technology28Note (3)You cannot create a generic arrayclass 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 Technology29Syntax Error:Cannot create a generic array of BoxReasonOperations such as instanceof and new are runtime operationsThey use a type at runtimeWith erasure type information is removed at runtimeSo these operations are MeaninglessAlthough, they may be possible
Spring 2014Sharif University of Technology30T ref = new T(); impossible which constructor?T[] elements = new T[size]; MeaninglessBox[] bsa = new Box[3]; Meaningless
Generics and Java 7Older 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 Technology31Further ReadingWildcards as type parametersJava generics vs. C++ templatesErasure is different in these languagesType Argument inferenceMore on erasure
TIJ is so better than Deitel in generics chapterMore Depth
Spring 2014Sharif University of Technology32Quiz!Spring 2014Sharif University of Technology33
QuizWrite a generic equals() and toString() methodsUse Pair class for at lPair class which can hold two objectsOverride appropriate east two different type-setsThe pair is orderedTwo ordered pairs are equal if their corresponding elements are equalSpring 2014Sharif University of Technology34A Note on Inheritanceclass 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 Technology35A Note on Inheritanceclass 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 Technology36A Note on Inheritanceclass 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 Technology37Pair class (Quiz)PairequalstoString
Spring 2014Sharif University of Technology38class 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 Technology39Pair 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 Technology40equals() methodpublic boolean equals(Pair pair) {return pair.first.equals(first) &&pair.second.equals(second); }What is wrong with this implementation?Spring 2014Sharif University of Technology41boolean equals(Pair pair) It should check for nullity of pairIt should check for nullity of pair.first and pair.secondIt should check for nullity of this.first and this.secondThis method does not override equals() It is overloading itCorrect signature:boolean equals(Object pair) What if parameter is not a Pair?
Spring 2014Sharif University of Technology42Type Checkingpublic 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 Technology43Spring 2014Sharif University of Technology44
Spring 2014Sharif University of Technology45