<<

Topic 5 Implementing Classes “And so,,p,gg from Europe, we get things such ... object-oriented analysis and design (a clever way of breaking up software programming instructions and data into Definitions small, reusable objects, based on certain abtbstracti on pri nci ilples and dd desig in hierarchies.)” -Michael A . Cusumano , The Business Of Software

CS 307 Fundamentals of Implementing Classes 1 CS 307 Fundamentals of Implementing Classes 2 Computer Science Computer Science

Object Oriented Programming Classes Are ... What i s o bject or iente d programm ing ? Another, simple definition: "Object-oriented programming is a method of A class is a programmer defined . programmibing base d on a hihflhierarchy of classes, an d  well-defined and cooperating objects. " A data type is a set of possible values and What is a class? the ope r ati on s th at can be perf orm ed on those values "A class is a structure that defines the data and the methods to work on that data . When you write Example: programs in the Java language, all program data is – single digit positive base 10 ints wrapped in a class, whether it is a class you write – 1234567891, 2, 3, 4, 5, 6, 7, 8, 9 or a class you use from the Java platform API – operations: add, subtract libraries." – Sun code camp – problems ? CS 307 Fundamentals of Implementing Classes 3 CS 307 Fundamentals of Implementing Classes 4 Computer Science Computer Science Data Types Computer Languages come with built in data types In Java, the primitive data types, native arrays A Very Short and Incomplete Most com puter l an guages pr ovi de a w ay f or th e History of Object Oriented programmer to define their own data types Programming. (OOP) – Java comes with a large library of classes So object oriented programming is a way of programming that is dominated by creating new data types to solve a problem. We will look at how to create a new data type CS 307 Fundamentals of Implementing Classes 5 CS 307 Fundamentals of Implementing Classes 6 Computer Science Computer Science

OOP is not new. OOP Languages Simu la 1 (1962 - 1965) an d Simu la 67 Smalltalk (1970s), Alan Kay's group at Xerox (1967) Norwegian Computing Center, Oslo, PARC NbOlNorway by Ole-JhJohan DhlDahl an dKitd Kristen Nygaard.

++ (early 1980s), Bjarne Stroustrup, Bell Labs

TiTuring Award dWi Winners - 2001 CS 307 Fundamentals of Implementing Classes 7 CS 307 Fundamentals of Implementing Classes 8 Computer Science Computer Science OOP Languages Program Design in OOP MdlModula – 3Ob3, Oberon, Eiff EifflJel, Java, C#, OOP breaks up problems based on the data Python types found in the problem – many languages have some Object – as opposed to breaking up the problem based on Oriented version or capability the algorithms involved One of the dominant styles for Given a problem statement, what things imppgppglementing complex programs with appear in the problem? large numbers of interacting The nouns of the problem are candidate components classes. – … but not the only programming paradigm and The actions and verbs of the problems are there are variations on object oriented programming candidate methods of the classes CS 307 Fundamentals of Implementing Classes 9 CS 307 Fundamentals of Implementing Classes 10 Computer Science Computer Science

Attendance Question 1 The process of taking a large problem and breaking it up into smaller parts is known as:

Short Object Oriented A. Functional programming Programming Design Example B. Object oriented programming C. Top down design D. Bottom up design EWE. Waterf fllall meth hdod

CS 307 Fundamentals of Implementing Classes 11 CS 307 Fundamentals of Implementing Classes 12 Computer Science Computer Science Monopoly

Individual Class Design If we had to start fhhfrom scratch what classes would we need to create?

CS 307 Fundamentals of Implementing Classes 13 CS 307 Fundamentals of Implementing Classes 14 Computer Science Computer Science

The Steps of Class Design Class Design  Requirements Classes s hou ld be cohihesive. – what is the problem to be solved – They should be designed to do one thing well. – detailed requirements lead to specifications Nouns may be classes Verbs signal behavior and thus methods (also defines a classes responsibilities) walkthrough scenarios to find nouns and verbs implementing and testing of classes Classes should be loosely coupled. design rather than implementation is normally the – Changing the internal implementation details of a class hardest part should not affect other classes. – loose coupling can also be achieved within a class itself – ppglanning for reuse

CS 307 Fundamentals of Implementing Classes 15 CS 307 Fundamentals of Implementing Classes 16 Computer Science Computer Science Encapsulation Design to Implementation Also know as separat ion o f concerns an d Design must me implemented using the information hiding syntax of the programming language  When creati ng new d a ta t ypes ( cl asses) the de ta ils In class example with a list of integers of the actual data and the way operations work is hidden from the other programmers who will use Slides in cl ude an oth er ex am pl e of cr eatin g a those new data types class to represent a playing die – So theyyy don't have to worry about them – So they can be changed without any ill effects (loose coupling) Encapsulation makes it easier to be able to use something – midiidthJStilicrowave, radio, ipod, the Java String class CS 307 Fundamentals of Implementing Classes 17 CS 307 Fundamentals of Implementing Classes 18 Computer Science Computer Science

The Problem with Arrays SIdttbhffiltitlSuppose I need to store a bunch of film titles from a file The Godfather AListofintsA List of ints The Princess Bride The Incredible

String[] titles = new String[100]; // I never know how much // space I need! I want the arrayyg to grow and shrink

CS 307 Fundamentals of Implementing Classes 19 CS 307 Fundamentals of Implementing Classes 20 Computer Science Computer Science Lists Attendance Question 2  I need a list. When adding a new element to a list  A list is a collection of items with a definite what should be the default location to order. add? Our ex am pl e will be a li st of in teger s. Design and then implement to demonstrate the Java syntax for creating a class. A. The beginning B. The end C. The middle D. A random location

CS 307 Fundamentals of Implementing Classes 21 CS 307 Fundamentals of Implementing Classes 22 Computer Science Computer Science

IntList Design Instance Variables CILiCreate a new, empty IntList ItInternal ldt data new IntList -> [] – also called instance variables because every The above is not code. It is a notation that shows instance (object) of this class has its own copy of what the results of operations. [] is an empty list. these – something to store the elements of the list add to a list. – size of internal storage container? [].add(1) -> [1] – if not what else is needed [1].add(5) -> [1, 5] Must be clear on the difference between the [1, 5].add(4) -> [1, 5, 4] internal data of an IntList object and the elements in a list have a definite order and a IntList that is being represented position. Whyyp make internal data private? – zero based position or 1 based positioning? CS 307 Fundamentals of Implementing Classes 23 CS 307 Fundamentals of Implementing Classes 24 Computer Science Computer Science Attendance Question 3 IntList aList = new IntList(); aList.add(42); aList.add(12); Our IntList class will have an instance variable aList.add(37); aList of ints (int[] container). What should the capacity of this internal array be? Abstract view of IntList A. less than or equal to the size of the list list of integers size 3 B. gr eat er th an or equal t o th e siz e of th e li st [42, 12, 37] container C. equal to the size of the list D. some fixed amount that never changes The wall of 42 12 37 0 0 0 0 0 0 0 E. 0 abstraction. 0 1 2 3 4 5 6 7 8 9

CS 307 Fundamentals of Implementing Classes 25 CS 307 Fundamentals of Implementing Classes 26 Computer Science Computer Science

Constructors Default add method For initialization of objects where to add? IntList constructors what if not enough space? – default [].add(3) -> [3] – initial cappyacity? [3]. add(5) ->[35]> [3, 5] redirecting to another constructor [3, 5].add(3) -> [3, 5, 3] this(10); class constants Testing, testing, testing! – what sttitatic means –a toString method would be useful

CS 307 Fundamentals of Implementing Classes 27 CS 307 Fundamentals of Implementing Classes 28 Computer Science Computer Science toString method Attendance Question 4  return a Java String of list What is output by the following code? empty list -> [] IntList list = new IntList(); one element -> [12] System.out.println( list.size() ); multiple elements -> [12, 0, 5, 4] A. 10 Beware the performance of String B. 0 concatenation. C. -1 StringBuffer alternative D. unknown E. No output due to runtime error.

CS 307 Fundamentals of Implementing Classes 29 CS 307 Fundamentals of Implementing Classes 30 Computer Science Computer Science

get and size methods insert method get add at someplace besides the end – access element from list [3, 5].insert(1, 4) -> [3, 4, 5] – preconditions ? [3, 5, 2].get(0) returns 3 where what [3, 5, 2].get(1) returns 5 [3, 4, 5].insert(0, 4) -> [4, 3, 4, 5] size preconditions? – number of elements in the list – Do not confuse with the capacity of the internal overload add? sttitorage container chance for internal loose coupling – The array is not the list! [4, 5, 2].s ize () returns 3 CS 307 Fundamentals of Implementing Classes 31 CS 307 Fundamentals of Implementing Classes 32 Computer Science Computer Science Attendance Question 5 remove method What is output by the following code? remove an element from the list based on IntList list = new IntList(); list.add(3); location list.insert(0, 4); [3, 4, 5].remove(0) -> [4, 5] list.insert(1, 1); list.add(();5); [[,,,,]3, 5, 6, 1, 2].remove ()(2) -> list.insert(2, 9); System.out.println( list.toString() ); [3, 5, 1, 2] A. [41395][4, 1, 3, 9, 5] preconditions? B. [3, 4, 1, 5, 9] return value? C. [4, 1, 9, 3, 5] D. [3, 1, 4, 9, 5] – accessor methods, mutator methods, and E. No output due to runtime error. mutator methods that return a value

CS 307 Fundamentals of Implementing Classes 33 CS 307 Fundamentals of Implementing Classes 34 Computer Science Computer Science

Attendance Question 6 insertAll method  What is output by the following code? add all elements of one list to another IntList list = new IntList(); starting at a specified location lis t.a dd(12); list.add(15); [5, 3, 7].insertAll(2, [2, 3]) -> list.add(12); [[,,,,]5, 3, 2, 3, 7] lis t.a dd(17); list.remove(1); The parameter [2, 3] would be unchanged. System.out.println( list ); A. [15, 17] Working with other objects of the same type B. [12, 17] – this? C. [12, 0, 12, 17] – where is pr itivate pr it?ivate? D. [12, 12, 17] E. [15, 12, 17] – loose coupling vs. performance

CS 307 Fundamentals of Implementing Classes 35 CS 307 Fundamentals of Implementing Classes 36 Computer Science Computer Science The Die Class Consider a class used to model a die What i s the i n terf ace? Wh at Class Design and Implementation – actions should a die be able Another Example tf?to perform?

This example will not be covered in class. The methods or behaviors can be broken up into constructors , mutators, accessors

CS 307 Fundamentals of Implementing Classes 37 CS 307 Fundamentals of Implementing Classes 38 Computer Science Computer Science

The Die Class Interface Visibility Modifiers  Constructors (used in creation of objects) All parts of a class have visibility modifiers – Java keywords – default, single int parameter to specify the – public,,p protected, pp,rivate, ((pgno modifier means package number of sides, int and boolean to determine if access) should roll – do not use these modifiers on local variables (syntax error) Mutators (f)(change state of objects) public means that constructor , method, or field may be accessed outside of the class. –roll – part o f the int erf ace Accessors (do not change state of objects) – constructors and methods are generally public – gg,g,getResult, getNumSides, toString private means that part of the class is hidden and  inaccessible by code outside of the class Public constants – part of the implementation – DEFAULT_ SIDES – data fields are generally private

CS 307 Fundamentals of Implementing Classes 39 CS 307 Fundamentals of Implementing Classes 40 Computer Science Computer Science The Die Class Implementation DieTester method Imppp,lementation is made up of constructor code, method code, and private data members of the class. public static void main(String[] args) {  final int NUM_ ROLLS = 50; scope of data members / instance variables final int TEN_SIDED = 10; – private data members may be used in any of the Die d1 = new Die(); Die d2 = new Die(); constructors or methods of a class Die d3 = new Die(TEN_ SIDED); Impl emen tati on i s hidden from users o f a c lass an d final int MAX_ROLL = d1.getNumSides() + can be changed without changing the interface or d2.getNumSides() + d3.getNumSides(); affecting clients (other classes that use this class) for(int i = 0; i < NUM_ROLLS; i++) – Example: Previous version of Die class, { d1.roll(); DieVersion1.java d2.roll(); System.out.println("d1: " + d1.getResult() Once Die class completed can be used in anything + " d2: " + d2.ge tResu lt() + " To ta l: " + (d1.getResult() + d2.getResult() ) ); requiring a Die or situation requiring random } numbers between 1 and N – Die Tes ter cl ass. Wha t d oes it do ?

CS 307 Fundamentals of Implementing Classes 41 CS 307 Fundamentals of Implementing Classes 42 Computer Science Computer Science

DieTester continued Correctness Sidetrack When creati ng th e publi c in ter face o f a c lass g ive int total = 0; int numRolls = 0; careful thought and consideration to the contract do { d1.roll() ; you ar e cr eatin g betw een your self an d user s (oth er d2.roll(); programmers) of your class d3.roll(); total = d1.getResult() + d2.getResult() Use preconditions to state what you assume to be + d3 .getResult(); numRolls++; true before a method is called } while(total != MAX_ROLL); – caller of the method is responsible for making sure these are true System.out.println("\n\nNumber of rolls to get " + MAX_ROLL + " was " + numRolls); Use postconditions to state what you guarantee to be true after the method is done if the preconditions are met – implementer of the method is responsible for making sure these are true

CS 307 Fundamentals of Implementing Classes 43 CS 307 Fundamentals of Implementing Classes 44 Computer Science Computer Science Precondition and Object Behavior - Instantiation Pos tconditi on Examp le CidhDiTConsider the DieTester c lass Die d1 = new Die(); /* pre: numSides > 1 Die d2 = new Die(); post: getResult() = 1, getNumSides() = sides Die d3 = new Die(10); */ When the new operator is invoked control is publiDi(itblic Die(int num Sid)Sides) transferred to the Die class and the specified { assert (numSides > 1) : “Violation of precondition: Die(int)”; constructor is executed, based on parameter matching iMyNumSides = numSides; Space(memory) is set aside for the new object's fields iMyResult = 1;  assert getResult() == 1 && getNumSides() == numSides; The memory address of the new object is passed } back and stored in the object variable (pointer) After creating the object, methods may be called on it.

CS 307 Fundamentals of Implementing Classes 45 CS 307 Fundamentals of Implementing Classes 46 Computer Science Computer Science

Creating Dice Objects Objects memory a Die object EDibjttdhitEvery Die object created has its own address instance of the variables declared in the 6 1 d1 class blueprint DieTester class. Sees iMySides iMyResult Die class. private int iMySides; interface of Die class Sees a Die object private int iMyResult; implementation. memory thus the term instance variable 6 1 (of Die class.) address the instance vars are part of the hidden d2 iMySides iMyResult implementation and may be of any data type a Die object – unless they are public, which is almost always a memory bad idea if you follow the tenets of information address 10 1 hiding and encapsulation d3 iMySides iMyResult CS 307 Fundamentals of Implementing Classes 47 CS 307 Fundamentals of Implementing Classes 48 Computer Science Computer Science Complex Objects The Implicit Parameter What if one of the instance variables is itself Consider this code from the Die class an object? public void roll()  { iMyResult = add to the Die class ourRandomNumGen.nextInt(iMySides) + 1; private String myName; } Taken in isolation this code is rather confusing. memory a Die object what is this iMyResult thing? address 6 1 memory address d1 – It's not a parameter or local variable iMySides iMyResult myName – why does it exist? d1 can hold the memory address – it belongs to the Die object that called this method of a Die object. The instance variable a String object – if there are numerous Die objects in existence myName inside a Die object can hold implementation – Which one is used depends on which object called the memory address of a String object details not shown the method.

CS 307 Fundamentals of Implementing Classes 49 CS 307 Fundamentals of Implementing Classes 50 Computer Science Computer Science

this The this Keyword Visually memory // in some c lass o ther than Die address When a method is called it may be necessary Die d3 = new Die(); for the calling object to be able to refer to itself d3.roll(); d3

– most likely so it can pass itself somewhere as a // in the Die class parameter public void roll() when an object calls a method an implicit { iMyResult = ourRandomNumGen.nextInt(iMySides) + 1; reference is assigned to the calling object /* OR the name of this implicit reference is this this. iMy Resu lt… a Die object this is a reference to the current calling object */ } memory and may be used as an object variable (may not address 6 1 declare it) this iMySides iMyResult

CS 307 Fundamentals of Implementing Classes 51 CS 307 Fundamentals of Implementing Classes 52 Computer Science Computer Science A Possible Equals Method An equals method ppqjjublic boolean equals(Object otherObject) { Die other = (Die)otherObject; return iMySides == other.iMySides working with objects of the same type in a && iMyResult== other. iMyResult class can be confusing && myName.equals( other.myName ); } write an equals method for the Die class. Declared Type of Parameter is Object not Die assume every Die has a myName instance override (replace) the equals method instead of variable as well as iMyNumber and iMySides overload (present an alternate version) – easier to create generic code we will see the equals method is inherited from the Object class access to another object's private instance variables?

CS 307 Fundamentals of Implementing Classes 53 CS 307 Fundamentals of Implementing Classes 54 Computer Science Computer Science

Another equals Methods A "Perfect" Equals Method  public boolean equals(Object otherObject) From Cay Horstmann's Core Java { Die other = (Die)otherObject; public boolean equals(Object otherObject) return this.iMySides == other.iMySides { // check if objects identical if( this == otherObject) && this.iMyNumber == other.iMyNumber return true; && this.myyq(y);Name.equals( other.myName ); // m ust r eturn f al se if ex pli ci t par am eter n ull } if(otherObject == null) return false; // if objects not of same type they cannot be equal if(getClass() != otherObject.getClass() ) Using the this keyword / reference to access the implicit parameters return false; instance variables is unnecessary. // we know otherObject is a non null Die If a meth od withi n th e same cl ass i s call ed withi n a meth od , th e Die other = (Die)otherObject; original calling object is still the calling object return iMySides == other.iMySides && iMyNumber == other.iMyNumber && my Name. equ als( other. my Name ); } CS 307 Fundamentals of Implementing Classes 55 CS 307 Fundamentals of Implementing Classes 56 Computer Science Computer Science the instanceof Operator Class Variables and Class Methods instanceof iJis a Java keywor d. Sometimes every object of a class does not part of a boolean statement need its own copy of a variable or constant public boolean equals(Object otherObj) The keyword static is used to specify { if otherObj instanceof Die class variables, constants, and methods { //now go and cast private static Random ourRandNumGen // rest of equals method = new Random(); } public static final int DEFAULT_ SIDES = 6; } The most prevalent use of static is for class Should not use instanceof in equals methods. constants. instanceof has its uses but not in equals – if the value can't be changed why should every objjpyggect have a copy of this non changing value because o f th e con tract of th e equal s meth od CS 307 Fundamentals of Implementing Classes 57 CS 307 Fundamentals of Implementing Classes 58 Computer Science Computer Science

Syntax for Accessing Class Variables Class Variables and Constants public class UseDieStatic { public static void main(String[] args) the Die class { System.out.println( "Die.DEFAULT_SIDES " + Die.DEFAULT_SIDES ); memory // Any attempt to access Die.ourRandNumGen 6 address // would generate a syntax error DEFAULT_SIDES ourRandNumGen Die d1 = new Die(();10);

a Random object System.out.println( "Die.DEFAULT_SIDES " All objects of type Die have + Die.DEFAULT_SIDES ); access tthlto the class vari iblables implementation Sys tem.ou t.pr in tln ( "d1. DEFAULT_ SIDES " and constants. details not shown + d1.DEFAULT_SIDES ); // regardless of the number of Die objects in A public class variable or constant // existence, there is only one copy of DEFAULT_SIDES may be referred to via the class name. // in the Die class } // end of main method } // end of UseDieStatic class CS 307 Fundamentals of Implementing Classes 59 CS 307 Fundamentals of Implementing Classes 60 Computer Science Computer Science Static Methods Static Methods Continued static has a somewhat different Since there is no implicit object parameter meaning when used in a method sent to the static method it does not have dldeclara tion access to a copy of any objects instance static methods may not manipulate any variables itinstance vari iblables – unlfless of course th thtbjtitat object is sent as an in non static methods, some object explicit parameter invo kes the me tho d Static methods are normally utility methods d3.roll(); or used to manipulate static variables ( class variables ) the object that makes the method call is  an implicit parameter to the method The Math and System classes are nothing but static methods

CS 307 Fundamentals of Implementing Classes 61 CS 307 Fundamentals of Implementing Classes 62 Computer Science Computer Science

static and this Why does this work (added to Die class) public class Die { public void outputSelf() { System.out.println( this ); } }

but this doesn ' t? public class StaticThis { public static void main(String[] args) { System.out.println( this ); } }

CS 307 Fundamentals of Implementing Classes 63 Computer Science