Presentation is loading. Please wait.

Presentation is loading. Please wait.

Abstract Data Types Chapter 1.

Similar presentations


Presentation on theme: "Abstract Data Types Chapter 1."— Presentation transcript:

1 Abstract Data Types Chapter 1

2 Today Data Types & Abstract Data Types Designing Systems and ADTs
use cases class-responsibility-collaboration cards (CRC) unified modeling language (UML) An Example ADT: the Bag More on interfaces

3 Data Structures Structure  arrangement
data structure  arrangement of data Some come with programming language data types Others developed by programmers some standardized—various Java packages others built to order

4 Data Types Computer languages offer data types
int, float, char, array of type, record of types, … Each type comes with some operations defined for it addition, multiplication, equality check, select an element, select a field, … Different languages/dialects may offer slightly different options

5 Abstract Data Types “Abstract” means not associated with any particular language/dialect/machine data types as they are in mathematics Data types implement ADTs int implements integer, float implements real usually restricted somehow Ideal is to make close to the model ADT

6 Abstraction Focus on what instead of how
car’s controls: gas, brakes, steering wheel, … what: accelerate, decelerate, turn, … how: gas? diesel? electric? drum? disk? gears? wire? for the driver, how doesn’t really matter driving an electric car much like driving any other design for the driver!

7 ADT Parts Domain of the ADT Operations Note: what values are there
functions defined over those values may involve other types Note: no decision on how to represent the values no decision on how to implement the operations

8 ADTs and Interfaces Interface specifies what can be done
Does not specify how it will be done Interface has no data fields BUT it’s designed with the data in mind operations are defined on the data operations take/modify/return data Java interfaces are data types

9 System Design Actors: who or what will use the system?
Scenarios: what will they be doing? University registration system actors: student & registrar scenarios: apply (student) enroll (registrar) add course (either) drop course (either)

10 Develop a Scenario “Use Case”: describe actor in scenario
Identify the nouns  look for classes/data Identify the verbs  look for methods Student adding a course: Student enters ID information System confirms student is registered Student selects course and section from list(s) If there is no time conflict: add course to student’s schedule

11 Develop a CRC Responsibilities Collaborations Student’s Schedule
Which scenarios? Methods in scenarios? Collaborations Which other classes are involved? Student’s Schedule add a section, remove a section, check for time conflict, … student has one schedule, but multiple sections

12 UML Diagrams Semi-formal way to represent information
class/interface name data methods + means public name: type Schedule (one or more sections) +addSection(s: Section) +removeSection(s: Section) +isTimeConflict(s: Section): boolean +show()

13 UML Diagrams Semi-formal way to represent information
lines/arrows for collaborations numbers on ends: how many of this for each each schedule has 0 to 10 sections (*  any #) arrows: schedule has sections; section no schedules Student Schedule Section Course 1 1 0..10 1 * *

14 <<interface>>
UML Diagrams Semi-formal way to represent information open-head arrows for inheritance interfaces labeled <<interface>> Student <<interface>> Measurable GradStudent UndergradStudent

15 Sample ADT: the Bag A finite collection of objects in no particular order, possibly with duplicates compare a list: in some particular order compare a set: no duplicates allowed Lists, sets and bags are all containers object to group other objects similar actions

16 Use Cases Assume we already went thru this process and discovered that we need a bag a bag is a fairly useful thing Only collaboration is the kind of things we want to put into the bag Only responsibilities are the methods for working with the bag

17 Bag CRC Responsibilities:
get # of items currently in bag see whether bag is empty add given object to bag remove given object from bag remove some unspecified object from bag empty the bag check whether some object is in the bag count duplicates of some object in the bag list all objects in the bag Collaboration: class of objects bag can contain

18 Things Can Go Wrong! Asked to remove item that’s not there
Asked for list element with negative index Need to decide what to do BAD things to do: ignore command don’t remove anything, don’t warn client try to “fix” the request take absolute value of index and return that item

19 Dealing with Unusual Conditions
Make client responsible to avoid it document the “precondition” on the operation Return a boolean value true  that worked; false  that didn’t Return a special value for failed operations not a valid return value! (null might work) Throw an exception

20 Bag Operation Failures
When adding an item, bag may be full return true if item was added, false otherwise When removing a specific item, not there return true if item was removed, false otherwise When removing “some” item, empty bag return null (NOTE: can’t keep nulls in the Bag) Incorporate these decisions into the design

21 Bag UML Diagram T is a “generic” type
each bag will specify its own “base” type Bag +getCurrentSize(): integer +isEmpty(): boolean +add(newEntry: T): boolean +remove(anEntry: T) : boolean +remove(): T +clear(): void +contains(anEnty: T): boolean +getFrequencyOf(enEntry: T): integer +toArray(): T[] T * *

22 Generic Types in Java You’ve seen these
ArrayList<Integer>, List<String>, … Use a generic name in the declaration usually one capital letter public class ArrayList<B> // B for “Base” public interface List<E> // E for “Element” public class Bag<T> // T for “Type” use that name in the method declarations public boolean add(T newEntry) { … }

23 Revised Bag UML Diagram
T is a “generic” type each bag will specify its own “base” type Bag<T> +getCurrentSize(): integer +isEmpty(): boolean +add(newEntry: T): boolean +remove(anEntry: T) : boolean +remove(): T +clear(): void +contains(anEnty: T): boolean +getFrequencyOf(enEntry: T): integer +toArray(): T[]

24 Bag Implementation/Interface
Want to allow multiple ways to implement an array, a linked list, a kind of structure that hasn’t even been invented yet! Each implementation is its own class ArrayBag, LinkedBag, QuantumBag, … For the ADT, we create an interface BagInterface

25 BagInterface public interface BagInterface<T> { public int getCurrentSize (); public boolean isEmpty (); public boolean add (T newEntry); public boolean remove (T anEntry); public T remove (); public void clear (); public boolean contains (T anEntry); public int getFrequency (T anEntry); public T[] toArray (); }

26 Document the Interface
Add javadoc comments to the interface Add javadoc comments to all methods (See the text/on-line code)

27 Using the ADT Bag We can use the ADT in our programs
On-line shopper program from text bag to put purchased items in base class Item (name and price) Overview of program add several items to bag remove items one at a time, adding to cost, until bag is empty

28 coins: BagInterface<Coin>
Using the ADT Bag Can use the ADT in other classes PiggyBank class from text instance variable: a Bag of Coins base class Coin (value and year minted) PiggyBank UML shake to see if empty drop a coin in shake till coin falls out PiggyBank coins: BagInterface<Coin> +isEmpty(): boolean +add(newEntry: Coin): boolean +remove(): Coin

29 Our First Bag Implementation
HumanBag a class that asks the user to hold the bag user adds/removes items, answers questions Only implements BagInterface<String> HumanBag not a generic type

30 HumanBag See code on-line
public class HumanBag implements BagInterface<String> { @Override public boolean add(String s) { Sopln("Add a(n) " + s " if you can."); return confirm("Did you add it? "); }

31 More on Interfaces Empty interfaces Constants in interfaces
Extending interfaces (Java 8) Static methods (Java 8) Default definitions the diamond problem lambda expressions

32 Interface Summary An interface is a data type
variables can have that data type including (especially) parameters for methods such variables (methods) called polymorphic An interface lists public methods each implementing class implements them each class has its own implementation each object in that class has that “skill setˮ

33 Empty Interfaces The Serializable interface has no methods
public interface Serializable {} Exists only to allow binary output ObjectOutputStream writeObject checks if (obj instanceof Serializable) if given non-Serializable object, throws NotSerializableException Must implement if writing to binary file public class TicTacToe implements Serializable

34 Constants in Interfaces
Interfaces allow constants to be declared public static final int MAX_SIZE = 10000; implement the interface  get the constant Constant should be part of the data type something necessary for every implementation .: MAX_SIZE probably not a good idea! interfaces for just constants are controversial use class with private constructor instead

35 Extending Interfaces Interfaces can be arranged using inheritance
public interface Measurable { public double getArea(); public double getPerimeter(); } public interface Polygonal extends Measurable { public int getNumberOfSides(); Polygonal has getArea and getPerimeter, too

36 Implementing Polygonal
Anything that implements Polygonal must define all the methods mentioned in Polygonal interface... public int getNumberOfSides() ...plus all those mentioned in Measurable public double getArea() public double getPerimeter()

37 And So On... Can extend an interface that extends another
just adding more methods to implement public interface RegularPolygonal extends Polygonal {...} Can extend more than one interface again, adding more methods to implement public interface FiniteSurface extends Measurable, Colourable { ... } Measurable Colourable Polygonal FiniteSurface RegularPolygonal

38 Combining Interfaces When one interface extends two others...
(or more than two others) ...it may not need any more methods it just puts those two (or more) interfaces together use empty braces (no new methods required) public interface FiniteSurface extends Measureable, Colourable {}

39 Exercise What methods must these classes implement?
public interface IA {public void is();} public interface IB {public int howMany();} public interface IC extends IB {public String whatKind();} public interface ID extends IA, IC {} public interface IE extends IA, IB {public void what();} public class A implements IE {...} public class B implements ID {...} public class C implements IA, IB {...}

40 Static Methods (Since Java 8) Can also add static methods
public interface Expression { // … missing code … public static int signum(double x) { return (int)Math.signum(x); } note: includes the definition! Must be called using interface name return Expression.signum(this.height – that.height) ;

41 Why Static Methods? Avoid need for classes of utility methods
Collections class has static methods for doing stuff with objects the implement Collection double max = Collections.max(myList); can put those methods in Collection interface double max = Collection.max(myList); benefit – one less letter to type (!!!) one less thing to import (maybe) can add static methods to existing interfaces

42 Default Method Definitions
(Since Java 8) Can add default definitions public default void clear() { while (!isEmpty()) { remove(); } note: includes definition Implementing classes don’t need to override but can override if they want to

43 Why Default Definitions
Simplify implementing the ADT one operation defined in terms of others clear out Bag  remove every item Bag is empty  # elements is zero give definition as a default can call other Bag operations we know the Bag will be able to do them because they're in the Bag interface And can add operations to existing interfaces just need to give a default definition

44 The Diamond Problem Problem of multiple inheritance
public interface Quaker { public default boolean isPacifist() { return true; } } public interface Republican { public default boolean isPacifist() { return false; } public class Nixon implements Quaker, Republican { // which definition of isPacifist()?

45 Conflicting Default Definitions
Two different definitions are available which to use? how to say which to use? Java requires the class to Override Nixon must override isPacifist method public class Nixon implements Quaker, Republican { @Override public boolean isPacifist() { return false; } }

46 Lambda Expressions Recall lambda expressions used for interfaces with just one method Java figures out what method is being defined OK if has default or static methods default and static methods have definitions so long as only one method with no definition i.e. one abstract method hence Single Abstract Method (SAM) requirement

47 Note on Style Everything in an interface is public (*)
not even allowed to say private public even if you don’t say say it anyway! All variables in interfaces are static static even if you don’t say Redundancy helps avoid errors (*) Changed in Java 9

48 Interfaces vs. Abstract Classes
v.8 interfaces more like abstract classes now can inherit method definitions now can have static methods can still leave some methods undefined But still different abstract classes can have instance variables … and class variables that aren’t final abstract class is for partial implementation interface still for defining a skill set

49 Java 9: Private Methods (Since Java 9) Can add private methods
static or non-static used by methods defined in this interface cannot be used by implementing classes signOf method in Measurable should be private Improves encapsulation can re-use code in default/static methods BY_PERIMETER and compareTo both use signOf

50 Questions


Download ppt "Abstract Data Types Chapter 1."

Similar presentations


Ads by Google