Java Interfaces, Lists and Generics essentials

Slides:



Advertisements
Similar presentations
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
Advertisements

Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Abstract Classes and Interfaces
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
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.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
ArrayList, Multidimensional Arrays
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
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.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Software Development
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
Advanced Generics and other niceties SOFTENG 251 Object Oriented Software Construction.
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:
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Interfaces and Inner Classes
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
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.
AD Lecture #3 Java Collection Framework 1.
Object Oriented Programming in Java Habib Rostami Lecture 7.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Modern Programming Tools And Techniques-I
Sixth Lecture ArrayList Abstract Class and Interface
slides created by Ethan Apter
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Generic programming in Java
slides created by Ethan Apter
slides created by Ethan Apter
ArrayLists 22-Feb-19.
Java Programming Language
CSE 143 Lecture 2 ArrayIntList, binary search
slides created by Ethan Apter
slides created by Ethan Apter and Marty Stepp
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Java Interfaces, Lists and Generics essentials SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Announcements Make sure you filled in last Friday’s session reports Assignment 2 (due 24th April) Demonstrate your work & understanding in lab Code correctness – either in lab or through dropbox Some updates to Wiki Additional resource link: Java Developers Almanac http://www.exampledepot.com/ - check it out! Exercise Bank – offline programming exercises; Utilise tutorial to go over any of these + assignment Lecture debriefing – anything I missed out during a particular lecture/Friday session, or you didn’t get a chance to ask Also Dols008’s lecture clarifications for Richard’s lectures SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Java Interfaces Interfaces are special “classes” with only abstract methods i.e. über-abstract classes if you will One major distinction: a class can “extend” (implement) multiple interfaces So what good is a “class” with no real methods? Interfaces are useful for defining a “signature”, or a “contract” of its implementing classes i.e. the methods in the interface define what the implementing class should do, i.e. expected to do Also a “cheap” way of supporting multiple inheritance SOFTENG 251 Object Oriented Software Construction

Flyer interface All birds can fly – so can some mammals But you can’t extend from both mammals and bird  introduce a Flyer interface public interface Flyer { public void fly(); } public class Bird extends Animal implements Flyer { public void fly() { System.out.println("Don’t look down"); } //etc... } Flyer <<interface>> +fly() Mammal public class FlyingSquirrel extends Mammal implements Flyer { public void fly() { System.out.println("Wheeee!!"); } //etc... } FlyingSquirrel +fly() +makeSound() #name Bird +fly() +getAge() -age Flyer[] flyers = new Flyers[2]; flyers[0] = new FlyingSquirrel("Yippee"); flyers[1] = new Bird(); for (Flyer flyer : flyers) { flyer.fly(); } SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction More Interface facts In a Java interface, you: can only define public abstract methods (if it’s not explicitly declared public or abstract, compiler automatically makes it so) can’t define instance variables can only define public, static and/or final variables Rules of inheritance and polymorphism apply to interfaces just as they do to normal classes e.g. an interface can inherit from another interface! public interface FastFlyer extends Flyer { public void hyperdrive(); } Class implementing FastFlyer must implement both fly() and hyperdrive() SOFTENG 251 Object Oriented Software Construction

Interface java.util.List Java’s version of the list data structure (non-generic – Java 1.4) This interface defines a contract for each of the operations of a list, i.e. What it takes in What it returns What the state of the list should be afterwards public interface List { public boolean add(Object o); public boolean add(int i, Object); public Object remove(int i); public Object remove(Object o); public Object get(int i); public int indexOf(Object o); public boolean contains(Object o); public int size(); public Iterator iterator(); //plus others } Up to actual implementers to fulfil the contract – in whatever way ArrayList, Vector (retrofitted) LinkedList ShoppingList SOFTENG 251 Object Oriented Software Construction

List operations & contracts add(x) true add(3,x) true a b c d x a b c x d 1 2 3 4 1 2 3 4 remove(x) false remove(c) true remove(1) b a b c d c a b c d 1 2 3 1 2 indexOf(x) -1 get(3) d indexOf(c) 2 a b c d a b c d c 1 2 3 1 2 3 4 ? 4 contains(b) true size() 4 contains(x) false a b c d a b c d 1 2 3 1 2 3 SOFTENG 251 Object Oriented Software Construction

ArrayList & LinkedList b c d e … a b c d e 1 2 3 4 5 6 1 2 3 4 public class ArrayList implements List { private Object[] elementData; private int size; ... //etc public boolean add(Object o) { elementData[size++] = o; return true; } public Object get(int i) { return elementData[i]; public int size() { return size; public class LinkedList implements List { private Entry header; private int size; ... //etc public boolean add(Object o) { addBefore(o,header); return true; } public Object get(int i) { return entry(i).element; public int size() { return size; SOFTENG 251 Object Oriented Software Construction

List and its implementations ArrayList and LinkedList override each of the abstract methods in List In overriding each method, both implementations satisfy the same contract but through very different means. E.g. +add(Object):boolean +remove(Object):boolean +get(int):Object +indexOf(Object):int +contains(Object):bool +size():int +iterator():Iterator etc… -instance variables… ArrayList +add(Object):boolean +remove(Object):boolean +get(int):Object +indexOf(Object):int +contains(Object):boolean +size():int +iterator():Iterator etc… List <<interface>> ArrayList’s remove(x): shift all elements from indexOf(x) + 1 to the left; size-- LinkedList’s remove(x): relink x’s previous node with x’s next node; size-- +add(Object):boolean +remove(Object):boolean +get(int):Object +indexOf(Object):int +contains(Object):bool +size():int +iterator():Iterator etc… -instance variables… LinkedList Both cases: list now is a concatenation of all elements before x and all elements after x. SOFTENG 251 Object Oriented Software Construction

Programming scenario MyLibrary List Item Book Movie CD Shirt Say we are writing a (very) simple personal “library” manager Organise a collection of items – books, movies, CD’s, etc. List items, sort items, add/remove items to library, etc We need some kind of collection to store these items Let’s use a List  ArrayList to be precise Priced <<interface>> MyLibrary List Item Book Movie CD Shirt SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction public class Item { protected String title; public Item(String title) { this.title = title; } public String getTitle() { return title; public class Book extends Item { private String author; public Book(String title, String author) { super(title); this.author = author; } public String getAuthor() { return author; public String toString() { return "Book: '" + title + “' by " + author; public class Movie extends Item { private int year; public Movie(String title, int year) { super(title); this.year = year; } public int getYear() { return year; public String toString() { return "Movie: " + title + " (" + year + ")"; public class CD extends Item implements Priced { ... public String getPrice() {...} } public interface Priced { public double getPrice(); } SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction A list of Items Book book = new Book("LOTR","Tolkien"); Movie movie = new Movie("Psycho",1960); CD cd = new CD("Ozomatli",2.50); List items = new ArrayList(); items.add(book); //element #0 items.add(movie); //element #1 items.add(cd); //element #2 Thanks to polymorphism: Variable item of type List can point to a value of type ArrayList We can pass in a Movie or Book as argument to add() as it accepts an Object However because get() returns an Object, we need to downcast the result to the appropriate subtype Book b = (Book)items.get(0); Item bookAsItem = (Item)items.get(0); Movie m = (Movie)items.get(1); Priced forSale = (Priced)items.get(2); public interface List { public boolean add(Object o); public Object get(int i); public int size(); //etc... } SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction List of Item’s public static void main(String[] args) { List items = new ArrayList(); populate(items); list(items); } public static void populate(List items) { items.add(new Movie("Psycho",1960)); items.add(new Book("LOTR","Toklien")); public static void list(List items) { for (int i = 0; i < items.size(); i++) { Item item = (Item)items.get(i); System.out.println(i+": "+item.getTitle()); We want items to only have objects of type Item (or its subclasses) What happens if it doesn't? SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Type safety public static void main(String[] args) { List items = new ArrayList(); populate(items); list(items); } public static void populate(List items) { items.add(new Movie("Psycho",1960)); items.add("Terminator"); //String! public static void list(List items) { for (int i = 0; i < items.size(); i++) { Item item = (Item)items.get(i); System.out.println(i+": "+item.getTitle()); What exactly would happen? (Will this compile?) Note: Remember that the downcasting here is legal because items.get() returns an Object and you can downcast from any superclass to any of its subclasses. SOFTENG 251 Object Oriented Software Construction

Compile-time vs. Runtime errors Moral of the story: we can’t rely on the compiler to detect/predict all errors (although we’d like to) What compilers can detect: Syntactic/”obvious” errors, e.g: accessing an undeclared variable; calling an undefined method; mismatching braces/brackets; assigning a value to a variable of incompatible type What compilers can't: Logical errors, unexpected behaviours only observable at runtime e.g. accessing a null field, bogus user input, nondeterministic code Most lead to exceptions being thrown like NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction What can we do instead? Create a specialised List for Item? public class ItemList { private List items; public boolean add(Item o) { items.add(o); } ... public Item get(int i) { return (Item) items.get(i); Repetitive Inefficient Hardly scalable public class StringList { private List items; public boolean add(String s) { items.add(s); } ... public String get(int i) { return (String)items.get(i); public class IntList { private List items; public boolean add(Integer i) { items.add(i); } ... public Integer get(int i) { return (Integer)items.get(i); SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Answer: Generics! With generics, we can make List a generic type By parameterising List with the type Item we are guaranteed that any instance of this special List would only contain objects of type Item (or its subclasses) Translation: List is a generic type, and it has one type parameter, which we call E public class List<E> { public boolean add(E o); public E get(int i); public int size(); } List<Item> items = new ArrayList<Item>(); ... items.add(new Movie("Psycho",1960)); for (int i = 0; i < items.size(); i++) { Item item = items.get(i); No casting necessary SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Generic ArrayList public class List<E> { public boolean add(E o); public E get(int i); public int size(); } Basically, all occurrences of Object are “replaced” by the type variable E Think of E as a placeholder for any possible type – just as a variable is a place-holder for any possible value Type variables can have any name – we just chose E because it’s nice and short Type variables themselves can be used to parameterise other generic types! (i.e. List<E>) public class ArrayList<E> implements List<E> { private E[] elementData; private int size; ... //stuff public boolean add(E o) { elementData[size++] = o; return true; } public E get(int i) { return elementData[i]; public int size() { return size; SOFTENG 251 Object Oriented Software Construction

Generics and type safety Good news: the compiler can help us prevent type errors The compiler enforces the parameterised type List<Item> to only accept and return instances of Item (or its subclasses) public static void main(String[] args) { List<Item> items = new ArrayList<Item>(); populate(items); list(items); } static void populate(List<Item> items) { items.add(new Movie("Psycho",1960)); items.add("Terminator"); static void list(List<Item> items) { for (int i = 0; i < items.size(); i++) { Item item = items.get(i); System.out.println(i+": "+item.getTitle()); String wtf = (String)items.get(i); COMPILE-TIME ERROR SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Review of lingo ‘Type parameter’ /‘Type variable’ ‘Non-generic type’ ‘Generic type’ public class Arraylist<E> { private E[] elementData; ... //stuff public boolean add(E o) { elementData[size++] = o; return true; } public E get(int i) { return elementData[i]; public class ArrayList { private Object[] elementData; ... //stuff public boolean add(Object o) { elementData[size++] = o; return true; } public Object get(int i) { return elementData[i]; ‘Parameterised type’ List<Item> items = new ArrayList<Item>(); ‘Type argument’ SOFTENG 251 Object Oriented Software Construction

Type variables/parameters Provide Item as type argument Provide "Hello" as argument new ArrayList<Item>() print("Hello"); value of type parameter E becomes Item value of variable str becomes "Hello" public class ArrayList<E> { private E[] elementData; ... //stuff public boolean add(E o) { elementData[size++] = o; return true; } public E get(int i) { return elementData[i]; private void print(String str) { ... int ln = str.length(); System.out.println(str); } SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Generic methods Define generic methods just as you define generic classes Example: reverse the elements from a given vector E.g. [a,b,c,d,e]  [e,d,c,b,a] List<Movie> movies = new ArrayList<Movie>(); List<String> words = new ArrayList<String>(); populate(movies); populate(words); List<Movie> seivom = reverse(movies); List<String> sdrow = this.<String>reverse(words); public<T> List<T> reverse(List<T> list) { List<T> rev = new ArrayList<T>(); for (int i = list.size() - 1; i >= 0; i --) { T item = list.get(i); rev.add(item); } return rev; Note the “proper” way of calling a generic method is to parameterise it like this. However usually the compiler can infer the type in question, allowing us to omit this construct. SOFTENG 251 Object Oriented Software Construction

(Non-generic alternative) Looks simpler! But realise obviously you won’t be able to retain type information using this method List movies = new ArrayList(); List words = new ArrayList(); populate(movies); populate(words); List seivom = reverse(movies); List sdrow = reverse(words); public List reverse(List list) { List rev = new ArrayList(); for (int i = list.size() - 1; i >= 0; i --) { Object item = list.get(i); rev.add(item); } return rev; SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Generic methods Bounded type parameters (e.g. <T extends Item>) allow restriction on type arguments Below: [Art,Bam,Apples,Crab,argh,Ache]  [Art,Apples,Ache] List<Movie> movies = new ArrayList<Movie>(); List<String> words = new ArrayList<String>(); populate(movies); populate(words); List<Movie> moviesA = startsWithA(movies); List<String> wordsA = startsWithA(words);  public<T extends Item> List<T> startsWithA(List<T> list) { List<T> filtered = new ArrayList<T>(); for (int i = 0; i < list.size(); i ++) { T item = list.get(i); if (item.getTitle().startsWith(“A”)) { filtered.add(item); } return filtered; Notice how we can call getTitle() on item, because we know from the type parameter T’s declaration that it extends Item SOFTENG 251 Object Oriented Software Construction

(Aside) Multiple type bounds Can use ‘&’ operator to define multiple type bounds List<Movie> movies = new ArrayList<Movie>(); List<CD> cds = new ArrayList<CD>(); ... pricedItems(movies); pricedItems(cds);  Movie is a subclass of Item, but not Priced public<T extends Item & Priced> void pricedItems(List<T> list) { for (int i = 0; i < list.size(); i ++) { T item = list.get(i); System.out.print("Loaning " + item.getTitle()); System.out.println(" at price " + item.getPrice()); } Notice how item (of type T) can now access all methods belonging to Item and Priced public interface Priced { public double getPrice(); } public class CD extends Item implements Priced { ... SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Try it yourself Revise lecture code examples Exercises in Wiki Writing a generic Pair<E1,E2> Writing a Chain<E> data structure A simple differencing tool Useful examples in the Java Almanac (see link from Wiki) SOFTENG 251 Object Oriented Software Construction

SOFTENG 251 Object Oriented Software Construction Tutorial idea Hands-on Generics: understanding what is/isn't possible with Generics. Observing compiler outputs. Focus on using generic types. List and HashMap good examples. The basics: compiler warnings with non-generic types, (good) compiler errors resulting from enforced generic types. Sub-typing: showing sub-typing of parameterised types acts differently from sub-typing of normal types Bounded and unbounded wildcards: how sub-typing can be done using these mechanisms SOFTENG 251 Object Oriented Software Construction