CSCE 314 Programming Languages Java Generics I Dr. Hyunyoung Lee 1.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Generics and the ArrayList Class
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.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Java Generics.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 10 Classes Continued
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Java Implementation: Part 3 Software Construction Lecture 8.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Chapters (ArrayList / Generic)
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Introduction to Generics
Inheritance and Access Control CS 162 (Summer 2009)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSCE 314 Programming Languages Java Generics II Dr. Hyunyoung Lee 1.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
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,
Introduction to Object-Oriented Programming Lesson 2.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
BY:- TOPS Technologies
Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Extending Classes.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Generic programming in Java
Java Inheritance.
CSCE 314: Programming Languages Dr. Dylan Shell
Java Programming Language
Presentation transcript:

CSCE 314 Programming Languages Java Generics I Dr. Hyunyoung Lee 1

Lee CSCE 314 TAMU Java Generics: History Pizza: , extended Java with generics, function pointers, class cases and pattern matching. GJ: 1998 derivative of Pizza; Generics the only extension. Java 1.5: Modeled after GJ. PolyJ: 1997, would have required changes to JVM. NextGen: 1998, avoids oddities of type erasure, still compatible with JVM and existing binaries. Extension of GJ. 2

Lee CSCE 314 TAMU Java Generics: Motivation Typesafe polymorphic containers Without generics: List l = new LinkedList(); l.add(new Integer(0)); Integer x = (Integer) l.iterator().next(); // need type cast String s = (String) l.iterator().next(); // bad cast exception With generics: List l = new LinkedList (); l.add(new Integer(0)); Integer x = l.iterator().next(); // no need for type cast String x = l.iterator().next(); // compile−time error 3 what happens without type cast?

Lee CSCE 314 TAMU Parameterized Classes public class Pair { //T, U: type variables, also formal type parameters private T a; private U b; public Pair(T t, U u) { a = t; b = u; } public T getFirst() { return a; } public U getSecond() { return b; } } Pair p = new Pair (0, ""); // Pair is an invocation/instance of the generic type // declaration with actual type arguments. Compare to Haskell: data Pair a b = Pair a b getFirst :: Pair a b -> a getFirst (Pair x y) = x getSecond :: Pair a b -> b getSecond (Pair x y) = y 4

Lee CSCE 314 TAMU (Mental) Model of Parametrized Classes public class Pair { private T a; private U b; public Pair(T t, U u) { a = t; b = u; } public T getFirst() { return a; } public U getSecond() { return b; } } Pair p = new pair (0, ""); public class Pair { private Object a; private Object b; public Pair(Object t, Object u) { a = t; b = u; } public Object getFirst() { return a; } public Object getSecond() { return b; } } 5

Lee CSCE 314 TAMU Parametrized Methods Example public class ArrayUtil {... public static void print(E[] a) { // generic method for (E e : a) System.out.print(e.toString() + " "); System.out.println(); } Rectangle[] rects =... ; String[] strs =... ; ArrayUtil.print(rects); ArrayUtil.print(strs); Explicit instantiation allowed as well: ArrayUtil. print(rects); ArrayUtil. print(strs); 6

Lee CSCE 314 TAMU Parametric Polymorphism Why does this work? public static void print(E[] a) { for (E e : a) System.out.print(e.toString() + " "); System.out.println(); } In Haskell, this did not work: print :: [a] -> IO () print ls = mapM_ (putStr. show) ls But this did: print :: Show a => [a] -> IO () print ls = mapM_ (putStr. show) ls 7

Lee CSCE 314 TAMU Parametric Polymorphism (Cont.) Java, too, needs constraints to type parameters Without constraints, only operations that are supported for all types can be applied to values whose types are type parameters. If no constraints, the constraint extends Object is assumed: public static void print(E[] a) { for (E e : a) System.out.print(e.toString() + " "); System.out.println(); } “E extends Object” justifies toString 8

Lee CSCE 314 TAMU Example of Constraints Erroneous: public static void print(List a, E threshold) { for (E e : a) if (e.compareTo(threshold) < 0)// type error !! System.out.print(e.toString() + " "); System.out.println(); } public static OKOK OKOK Comparable interface itself is really parametrized (to be discussed) 9

Lee CSCE 314 TAMU Type Parameter with Multiple Bounds Multiple bounds for a single type parameter allowed: class SortedList {... } In, extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces) If one of the bounds is a class, it must be specified first Compare with multiple class constraints in Haskell: smallToString :: (Show a, Ord a) => a -> [a] -> [String] smallToString x xs = map show (filter (< x) xs) *Main> smallToString 5 [1,2,3,4,5,6] ["1","2","3","4"] 10

Lee CSCE 314 TAMU Unnamed Type Parameters - Wildcards static void printAll (List l) { for (Object o : l) System.out.println(o); } Wildcards are both a convenience feature (more concise syntax), and to add support for co/contravariance for type parameters (discussed later). 11

Lee CSCE 314 TAMU Plain Bounded Quantification Example (in C++ like syntax) class Point { public int x; public int y; } class ColorPoint extends Point { public int color; } This establishes: ColorPoint <: Point Peter Canning, William Cook, Walter Hill, Walter Olthoff, and John C. Mitchell. “F-bounded polymorphism for object- oriented programming.” Functional Programming Languages and Computer Architecture, pages 273–280, ACM,

Lee CSCE 314 TAMU Subtyping Example class Point { public int x; public int y; } class ColorPoint extends Point { public int color; } Point move(Point a, int dx, int dy) { a.x += dx; a.y += dy; return a; }... Point p = new Point(); p.x = 0; p.y = 0; p = move(p, 1, 2); ColorPoint cp = new ColorPoint(); cp.x = 0; cp.y = 0; cp.color = 0; cp = move(cp, 1, 2); // Type error! p = move(cp, 1, 2); // OK! With just subtyping, the exact type of cp is lost when passed to and returned from move() 13

Lee CSCE 314 TAMU Bounded Quantification Subtype polymorphism in itself is not sufficient A possible fix to this losing of type accuracy is to use parametric polymorphism (instead of subtype polymorphism): T move(T a, int dx, int dy) { a.x += dx; a.y += dy; return a; } Access to members x and y, and operations on them must be justified by some constraints T move(T a, int dx, int dy) { a.x += dx; a.y += dy; return a; } Simple constraint: T itself does not occur in the constraint (in the literature, this is sometimes referred to as bounded quantification [Cardelli, Wegner 85]) Constraint is fixed for all instantiations, which turns out to be too limited 14

Lee CSCE 314 TAMU Problems with Bounded Quantification interface Movable { Movable move(int x, int y); } Define function translate that takes any Movable object, and returns another one of the same type, moved one unit along both axis. translate should have (roughly) the type: ∀ T T First attempt (does not work): T translate(T m) { return m.move(1, 1); } // type error! move is (essentially) of type (Movable, int, int) -> Movable So, we again hit the problem of subtyping losing information! 15

Lee CSCE 314 TAMU Binary Method Problem Assume the following interface: interface EqComparable { bool eq(EqComparable o); } Task: Define a function noteq to compute the negation of eq This is what bounded quantification enables: bool noteq(T t, T u) { return !t.eq(u); } Now define a class MyInt which is EqComparable class MyInt implements EqComparable { bool eq(MyInt o) {... }// not a valid override bool eq(EqComparable o) {... } // meaningless comparison } 16

Lee CSCE 314 TAMU Detour: Rules for Method Overriding (1) 1.The argument list should be exactly the same as that of the overridden method. 2.The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. 3.The access level cannot be more restrictive than that of the overridden method. For example: if the superclass method is declared public then the overridding method in the subclass cannot be either private or protected. 17

Lee CSCE 314 TAMU Detour: Rules for Method Overriding (2) 4.Constructors cannot be overridden. 5.A method declared final cannot be overridden. 6.A method declared static cannot be overridden but can be re-declared. 7.If a method cannot be inherited, then it cannot be overridden. 18

Lee CSCE 314 TAMU Detour: Rules for Method Overriding (3) 8.A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. 9.A subclass in a different package can only override the non-final methods declared public or protected. 10.An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. 19

Lee CSCE 314 TAMU F-Bounded Quantification F-bounded quantification allows the type parameter being constrained to appear in its own bound: > The unsuccessful translate example: T translate(T m) { return m.move(1, 1); } can now be written as: interface Movable { T move(int x, int y); } > T translate (T m) { return m.move(1, 1); } 20

Lee CSCE 314 TAMU Binary Method Problem Revisited Assume the following interface: interface EqComparable { bool eq(EqComparable); } bool noteq(T t, T u){ return !t.eq(u); } Define a class MyInt which is EqComparable class MyInt implements EqComparable { bool eq(MyInt) {... }// not a valid override bool eq(EqComparable) {... } // meaningless comparison } Now, using F-bounds: interface EqComparable { bool eq(T); } > bool noteq (T t, T u) { return !t.eq(u); } class MyInt implements EqComparable { bool eq(MyInt) {... } } 21

Lee CSCE 314 TAMU Another Example: generic sort > void sort(T[] v) { for(int i = 0; i < v.length; i++) for(int j = 0; j < i; j++) if (v[j].compareTo(v[i]) < 0) swap(v, i, j); } 22

Lee CSCE 314 TAMU Summary Minor generalizations of F-bounded polymorphism are the backbone of Java, C#, and Eiffel generics The essential feature in F-bounds is that bounds are generic too — they change along the argument that is being tested for Subtyping is one way of expressing constraints, there are others (Haskell type classes, C++ concepts, ML signatures) 23