Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Interfaces, Lists and Generics essentials

Similar presentations


Presentation on theme: "Java Interfaces, Lists and Generics essentials"— Presentation transcript:

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

2 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 - 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

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

24 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

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

26 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

27 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


Download ppt "Java Interfaces, Lists and Generics essentials"

Similar presentations


Ads by Google