ADSA: Subtypes/7 1 241-423 Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
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.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
CPSC150 Abstract Classes and Interfaces Chapter 10.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Arrays. Example Write a program to keep track of all students’ scores on exam 1. Need a list of everyone’s score Declare 14 double variables? What about.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
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.
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.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Chapter 18 Java Collections Framework
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Generics. What is Generics Collections can store Objects of any Type Generics restricts the Objects to be put in a collection Generics ease identification.
Java Basics.  To checkout, use: svn co scb07f12/UTORid  Before starting coding always use: svn update.
ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.
Generics CompSci 230 S Software Construction.
Types in programming languages1 What are types, and why do we need them?
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
Polymorphism (generics) CSE 331 University of Washington.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Typecasting References Computer Science 3 Gerb Reference: Objective: Understand how to use the Object class in Java in the context of ArrayLists.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
JAC444: Intro to Java Arrays and Vectors Tim McKenna
CS/ENGRD 2110 FALL 2015 Lecture 6: Consequence of type, casting; function equals 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.
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
Chapter 9 Introduction to Arrays Fundamentals of Java.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
More on Java Generics Multiple Generic Types Bounded Generic Types
Generics and Subtyping
Generics and Type Parameters
Lecture 19 - Inheritance (Contd).
Generics (Parametric Polymorphism)
Generics.
Generic programming in Java
Review: libraries and packages
Chapter 19 Generics.
Subtype Substitution Principle
Presentation transcript:

ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce covariance and contravariance Semester 2, Subtypes/subclassing and Generics

ADSA: Subtypes/7 2 Contents 1. The Substitution Principle 2. Subtyping of An Entire Collection 3. Subtyping/subclassing Terminology 4. Covariance: ? extends 5. Contravariance: ? super 6. The Get and Put Principle (PECS) 7. No Instance Creation with ?

ADSA: Subtypes/ The Substitution Principle You can assign an object of any subclass to a class reference (variable). Integer i = new Integer(6); Number n = i; Number FloatInteger extends Number reference Integer object n i

ADSA: Subtypes/7 4 Apple a = new Apple(); Fruit f = a; Fruit AppleStrawberry extends Fruit reference Apple object f a

ADSA: Subtypes/7 5 Subtyping of Collection Elements We can add an integer or a double to a collection of Numbers, because Integer and Double are subclasses of Number. List nums = new ArrayList (); nums.add(2); nums.add(3.14); // OK

ADSA: Subtypes/7 6 List reference Integer object nums... Double object List object Number references

ADSA: Subtypes/ Subtyping of An Entire Collection You might think that since Integer is a subclass of Number, then List is a subclass of List. NO!!! List ints = Arrays.asList(2, 3); List nums = ints; // compile-time err

ADSA: Subtypes/7 8 List reference Integer object nums... Double object List object Integer references 3 2 ints

ADSA: Subtypes/7 9 Why? It's to prevent run-time errors such as the following: List ints = new Integer[] {1,2}; List nums = ints; // compile-time error nums.add(3.12); // run-time error (not reached)

ADSA: Subtypes/7 10 Another Example List apples =...; List fruits = apples; // compile-time error

ADSA: Subtypes/7 11 Just to confuse matters, Integer[] is a subclass of Number[]. Integer[] ints = new Integer[] {1,2,3}; Number[] nums = ints; // OK nums[2] = 3.12; // run-time error (will be reached) Arrays are Different

ADSA: Subtypes/ Subtyping/subclassing Terminology Covariance: a class reference (variable) can point to a 'narrower' subclass object –e.g. Fruit f = new Apple(); –narrower means "more specific" Contravariance: a class reference (variable) can point to a 'wider' superclass object –e.g from Integer to Number –not common in Java Invariant: not able to convert

ADSA: Subtypes/7 13 Arrays are covariant: –Integer[] is also a Number[] Basic Generic classes are not covariant and not contravariant: they are invariant For example: –List is not a subclass List –Also List is not a subclass of List

ADSA: Subtypes/7 14 Adding Covariance and Contravariance It is useful to allow covariance and contravariance in collections, so the Java designers added: –? extends (extends wildcard) for covariance –? super (super wildcard) for contravariance

ADSA: Subtypes/ Covariance: ? extends List ints = Arrays.asList(1,2); List nums = ints; // OK " ? extends Number " means that it is OK to assign a subclass collection of Number to nums –in this case, a collection of Integers

ADSA: Subtypes/7 16 But we cannot put elements into the collection... List ints = Arrays.asList(1,2); List nums = ints; // OK nums.add(3.12); // compile-time error This is the array situation, but with one big difference –the error is caught at compile-time

ADSA: Subtypes/7 17 Another ? Extends Example List apples = new ArrayList (); List fs = apples; // OK fs.add(new Strawberry()); //compile-time err The code won't compile even if we try to add an Apple or a Fruit instance fs.add(new Apple()); //compile-time err fs.add(new Fruit()); //compile-time err

ADSA: Subtypes/7 18 The restriction is because the compiler only knows that fs refers to a collection subclass of Fruit, but not which one.

ADSA: Subtypes/7 19 The only thing we can add is null: fruits.add(null); // ok We can get data out of the structure but only as a Fruit instance (the ? extends class): Fruit get = fruits.get(0);

ADSA: Subtypes/7 20 Summary of ? extends It allows the assignment of a subclass collection to a superclass collection reference, but no element assignments are possible –quite restrictive Values can be removed, as instances of the superclass –useful Good for 'getting' Good for 'getting'

ADSA: Subtypes/ Contravariance: ? super List objs = Arrays. asList(1,"two"); List vals = objs; vats.add(3); // ok ? super allows a superclass collection of Integer to be assigned to vals –in this case, a list of Objects And you can add subclass elements to the collection later.

ADSA: Subtypes/7 22 Another ? super example List fruits = new ArrayList (); List apps = fruits; apps.add(new Apple()); // OK apps.add(new GreenApple()); // OK apps.add(new Fruit()); // compile-time error apps.add(new Object()); // compile-time error Only subclass elements of Apple can be added.

ADSA: Subtypes/7 23 Why? The compiler knows that apps refers to a superclass collection of Apple. It does not know which class, but all superclasses of Apple can store subclasses of Apple as new elements.

ADSA: Subtypes/7 24 Get Restriction with ? Super You can only get elements out of a ? super object as values of class Object: Object ob1 = fruits.get(0); Object ob2 = fruits.get(1); Fruit f = (Fruit) fruits.get(0); // compile-time err

ADSA: Subtypes/7 25 Another Example List objs = Arrays. asList(1,"two"); List ints = objs; String str = ""; for (Object obj : ints) str += obj.toString(); // Object method // str is "1two"

ADSA: Subtypes/7 26 Summary of ? super It allows the assignment of a superclass collection to a subclass reference, and further subclass additions are possible –useful Values can only be removed as Object instances –quite restrictive Good for 'putting' Good for 'putting'

ADSA: Subtypes/ The Get and Put Principle (PECS) –use ? extends when you only get values out of a collection; i.e. is a producer –use ? super when you only put values into a collection; i.e. is a consumer –don't use a wildcard when you both get and put PECS comes from "Producer Extends, Consumer Super"

ADSA: Subtypes/7 28 ? extends Function example public static double sum( Collection nums) { double s = 0.0; for (Number num : nums) s += num.doubleValue(); return s; } PECS producer (a Number method)

ADSA: Subtypes/7 29 The following calls are legal: List ints = Arrays.asList(1, 2, 3); double d = sum(ints); // == 6.0; List doubles = Arrays.asList(2.78, 3.14); double d = sum(doubles); // == 5.92; List nums = Arrays. asList(1, 2, 2.78, 3.14); double d = sum(nums); // == 8.92; The first two calls would not be legal if ? extends was not used.

ADSA: Subtypes/7 30 ? super function example public static void count( Collection ints, int n) { for (int i = 0; i < n; i++) ints.add(i); } PECS consumer

ADSA: Subtypes/7 31 The following calls are legal: List ints = new ArrayList (); count(ints, 5); // ints.toString().equals("[0, 1, 2, 3, 4]"); List nums = new ArrayList (); count(nums, 5); nums.add(5.0); // nums.toString().equals("[0, 1, 2, 3, 4, 5.0]"); List objs = new ArrayList (); count(objs, 5); objs.add("five"); // objs.toString().equals("[0, 1, 2, 3, 4, five]"); The last two calls need ? super in count()

ADSA: Subtypes/7 32 No wildcard example public static double sumCount( Collection nums, int n) { count(nums, n); return sum(nums); } The nums collection is passed to both sum() and count(), so its element class must both extend Number (as sum() requires) and be super to Integer (as count() requires). Number Integer ? extend ? super

ADSA: Subtypes/7 33 The only two classes that satisfy both of these constraints are Number and Integer, and I picked the first. A sample call: List nums = new ArrayList (); double sum = sumCount(nums,5); Number Integer ? extend ? super

ADSA: Subtypes/7 34 Using both ? extends and ? super public static void copy( List dst, List src) { for (int i = 0; i < src.size(); i++) dst.set(i, src.get(i)); } the destination list may already contains elements of any class that is a superclass of Integer the source list will have elements of any class that is a subclass of Integer. PECS

ADSA: Subtypes/7 35 A sample call: List objs = Arrays. asList(2, 3.14, "four"); List ints = Arrays.asList(5, 6); Collections.copy(objs, ints); // objs is "[5, 6, four]"

ADSA: Subtypes/ No Instance Creation with ? For example, the following are illegal: List list = new ArrayList (); // compile-time error Map map = new HashMap (); // compile-time error

ADSA: Subtypes/7 37 Usually we create a concrete collection first, even if we use wildcards later: List nums = new ArrayList (); List sink = nums; // OK for (int i=0; i<10; i++) sink.add(i);