© 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements.

Slides:



Advertisements
Similar presentations
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Interfaces A Java interface is a collection
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Software Development Software Life Cycle UML Diagrams.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
Classes, Encapsulation, Methods and Constructors
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 10 Classes Continued
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Object Oriented Software Development
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Object Oriented Design and UML
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
© 2004 Pearson Addison-Wesley. All rights reserved November 9, 2007 Method Design & Method Overloading ComS 207: Programming I (in Java) Iowa State University,
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
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.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 6 Object-Oriented Design Part 1. © 2004 Pearson Addison-Wesley. All rights reserved2/42 Object-Oriented Design Now we can extend our discussion.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Inheritance Reading for this Lecture: L&L 6.4 – 6.5.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
Programming in Java (COP 2250) Lecture 14 & 15 Chengyong Yang Fall, 2005.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Static class members.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
1 Object-Oriented Design Now we can extend our discussion of the design of classes and objects Chapter 6 focuses on: software development activities determining.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
© 2004 Pearson Addison-Wesley. All rights reserved October 31, 2007 Static Class Members ComS 207: Programming I (in Java) Iowa State University, FALL.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
© 2004 Pearson Addison-Wesley. All rights reserved November 2, 2007 Class Relationships ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Interfaces November 6, 2006 ComS 207: Programming I (in Java)
About the Presentations
Java Coding 8 David Davenport Computer Eng. Dept.,
Object Oriented Programming
Chapter 5 – Writing Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 4: Writing classes
Static Class Members March 29, 2006 ComS 207: Programming I (in Java)
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming Review
Java Coding 8 David Davenport Computer Eng. Dept.,
Object-Oriented Design Part 2
Presentation transcript:

© 2004 Pearson Addison-Wesley. All rights reserved6-1 Program Development In your CS102 project, and in many others, the basic activities are:  requirements – WHAT to do  design (UI and detailed design) – HOW to do  implementation – DO it  testing – CHECK errors and DEBUG They overlap and interact Requirements and Design stages are extremely important

© 2004 Pearson Addison-Wesley. All rights reserved6-2 Requirements Tasks that a program must accomplish What to do, not how to do it Possibly Problem description Functionalities and feature lists Use-case descriptions

© 2004 Pearson Addison-Wesley. All rights reserved6-3 Design How a program will accomplish its requirements  Break the solution into manageable pieces  What each piece will do  Which classes and objects are needed, and how they will interact  Detailed design include how individual methods will accomplish their tasks UI Design  How will it look like? How the system will interact with the user?  Storyboard, illustration, description of the interactions

© 2004 Pearson Addison-Wesley. All rights reserved6-4 Implementation, Testing, Debugging, Maintenance Implementation: translating a design into source code Testing attempts to find errors  Ensure to solve the intended problem under all the constraints specified in the requirements Debugging: determining the cause of a problem and fixing it Maintenance

6-5 HangMan: Partial Requirements In the game of Hangman the player must find a word chosen secretly by the program. The player can try one letter at a time and the program says how many times and where the letter appears in the secret word. If the player tries more than a certain number of incorrect letters (i.e. letters which do not appear in the secret word), they lose the game and the program tells them the secret word, otherwise they continue until they uncover the complete word. * by David Davenport

6-6 HangMan: Partial Requirements Usually, players are able to see the partially formed word made by the letters so far correctly guessed, any unknown letters being left blank. They may also be able to see the set of all letters that might be in the word (with those already used possibly being removed), as well as the number of incorrect tries made so far (this is often shown graphically, by the number of visible body parts of a cartoon character which is hung when complete -hence the name of the game!)

6-7 HangMan: Partial Design class Hangman constructors  + Hangman() // default max 6 incorrect tries, English alphabet, // chooses secretWord from fixed list. set  all letters to English alphabet  max allowed incorrect tries to 6, no of incorrect tries to 0,  used letters to empty set,  secret word by calling choose-secret-word method  knowsofar to StringBuffer of same length as secret word, but all characters are stars ('*').

6-8 HangMan: Partial Design properties  secretWord : StringBuffer  allLetters : StringBuffer  usedletters : StringBuffer  numberOfIncorrectTries : int  maxAllowedIncorrectTries : int  knownSoFar : StringBuffer // secretWord but with chars not yet found blanked out

6-9 HangMan: Partial Design methods  + getAllLetters() : String  + getUsedLetters() : String  + getNumOfIncorrectTries() : int  + getMaxAllowedIncorrectTries : int  + getKnownSoFar() : String // returns partial word formed with known letters only  + tryThis( letter) : int // returns number of occurrences of letter in secretWord  + isGameOver() : boolean  + hasLost() : boolean  - chooseSecretWord() // initially use fixed list, called from constructor

6-10 HangMan: Notes on a Method tryThis(letter): Returns number of times the letter occurs in the secret word. Adds letter to used letters. Updates known so far to show the letter at each position it exists in secret word. If the letter is not in secret word then increment number of incorrect tries. Method should return error values to indicate if the letter is not valid (-1), if the letter was already used (-2), and indicate if game over (-3).

6-11 HangMan Game: Main method Need a main method to start the game by  Creating instance of Hangman class  Calling its methods Allow the user to interact with it  UI -- could be as simple as the text mode using the keyboard only, or more sophisticated graphics The program must repeatedly get letters from the user and try them  A while loop until the game is complete

6/11/2016 CS101 - Algorithms & Programming I 12 Java OOP Software Software System  Set of objects  Which interact with each other One object will send a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done.) This corresponds to calling one of the second object’s methods! Created (instantiated) from class definitions Person AyseDavid “David” David: Say your name

6/11/2016 CS101 - Algorithms & Programming I 13 Coding Java Classes // header public class Person { // properties // constructors // methods } public void sayName() { System.out.println( name); } Stringname; intage; doublesalary; Stringcomments; public Person( StringtheName, inttheAge ) { name = theName; age = theAge; comments = “”; }

6/11/2016 CS101 - Algorithms & Programming I 14 Coding Java Classes public double getNetSalary() { double netSalary; netSalary = salary - TAX; return netSalary; } public String getName() { return name; } public String getComments() { return comments; } public void setComments( String someText) { comments = someText; } “get” & “set” methods for some properties (no setName!) Variables which are not parameters or properties must be defined locally. public void increaseAge() { age = age + 1; }

6/11/2016 CS101 - Algorithms & Programming I 15 Creating & Using Objects Always  Declare variable to “hold” object  Create object using “new” statement  Call object’s methods “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} Person aStudent; aStudent = new Person( “Ayse”, 18); aStudent.sayName(); Put this in method of another class, (e.g main method)

6/11/2016 CS101 - Algorithms & Programming I 16 Creating & Using Objects Person aStudent; aStudent = new Person( “Ayse”, 18); Person friend; friend = new Person( “David”, 22); “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} “David” name: 22 age: 0.0 salary: “” comments: friend {Person} friend.increaseAge(); aStudent.setComments( “Good student”); 23 “Good student”

© 2004 Pearson Addison-Wesley. All rights reserved6-17 Identifying Classes and Objects The core activity: Determine the classes and objects Reuse the classes (a class library, etc.) One way to identify potential classes is to identify the objects discussed in the requirements Objects are generally nouns, and the services that an object provides are generally verbs

© 2004 Pearson Addison-Wesley. All rights reserved6-18 Identifying Classes and Objects A partial requirements document: The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A. Of course, not all nouns will correspond to a class or object in the final solution

© 2004 Pearson Addison-Wesley. All rights reserved6-19 Identifying Classes and Objects Remember: A class is a concept for a group (classification) of objects with the same behaviors  Singular nouns: Coin, Student, Employee Need to decide whether something should be represented as a class  Should Address of an employee be an instance variable or an object itself? When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities

© 2004 Pearson Addison-Wesley. All rights reserved6-20 Identifying Classes and Objects Define the classes with the proper amount of detail May be unnecessary to create separate classes for each type of appliance in a house  Sufficient to define a more general Appliance class with appropriate instance data It all depends on the details of the problem being solved

Example: A Card Game* Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. * by David Davenport

Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. Example: A Card Game

Picture it… Objects the Game? Pack of cards Players 1, 2, 3 & 4 the Table? Score card? (Player 1, 2, 3 & 4 scores) Players 1, 2, 3 & 4 Cards on table Players 1, 2, 3 & 4 Cards in hand player score Table player Pack of cards

Classes CleverGame Pack of cards 4 Players Scorecard (with 4 scores on) 4 Piles of cards on table ScoreCard Set of scores Player Name Set of cards in hand Cards Collection of cards Card Face value Suit

Design & implement a program to play a simple game of cards between four players. To begin, a full pack of cards are shuffled and dealt face- down to the players. The game then proceeds in rounds. For each round, players play the top card from their hand and add it face-up to a pile on the table in front of them. The player who plays the highest value card is the winner of the round and their score is incremented by one. When all of the cards have been played the player with the highest score is declared the winner of the game. Example: A Card Game*

Simple Game class properties Pack of cards 4 Players 4 Scores 4 Piles of cards on table constructor ( 4 players) creates the game with the given players methods playGame() plays a complete game sets scores getScore( player number) returns players score Represents a single card game played by 4 players

CleverGame class properties Pack of cards, 4 Players ScoreCard, 4 Piles of cards on table constructor ( 4 players) creates the game with the given players Methods + playTurn(Player, Card) : boolean + isTurnOf(Player) : boolean + isGameOver() : boolean + getScore( playerNumber) : int + getName( playerNumber) : String + getRoundNo() : int + getTurnOfPlayerNo() : int + getWinners() : set of Player Represents a single card game played by 4 players

Player class properties name set of cards in hand constructor ( name) creates player with name & empty hand methods getName() returns players name add( Card) add the card to players hand playCard() removes and returns the top card from the players hand Represents a single player for a card game

ScoreCard class properties Set of scores constructor ( noOfScores) initialises scorecard with noOfScores entries all set to zero methods + getScore(scoreNo) : int returns specified score + update( scoreNo, amount) add amount to scoreNo Represents a ScoreCard for a card game

Cards class properties Collection of cards constructor () creates a collection of cards with no cards in it! methods getTopCard() removes & returns top card from collection addTopCard( Card) adds the card to the collection createFullPackOfCards() shuffle() randomises order of cards in collection Represents a set of zero or more playing cards

Card class properties faceValue suit constructor ( faceValue, suit) creates card with given face value & suit constructor ( cardNumber) creates card with given position number in ordered pack! methods getFaceValue() returns faceValue getSuit() returns suit toString() Represents a single playing card

Playing the Game Algorithm for playGame method Create the pack of cards Shuffle the pack Deal all the pack between the players Create empty piles of cards on table Set all players scores to zero For each round (until players have no cards left) Each player plays card by adding it to their pile on table Find biggest value card on top of piles on table Increment scores of players who played cards with biggest value

Playing the Game public void initGame() // create new pack & shuffle // create empty set of cards on table for each player // deal all cards to players // create score card // create piles of cards on table // set round no to 0 // setturn of player no to 0

Playing the Game public boolean playTurn( SimplePlayer p, Card c) // if game is over return false // if it's not p's turn return false // p's turn so take p's card & put on table // if not end of round then // move to next players turn else // end of round, update scores & // if not end of game then // move to next round & next player's turn return true private void updateScores() // find max of cards just placed on table // increment scores of player(s) with max card(s)

© 2004 Pearson Addison-Wesley. All rights reserved6-35 Static Methods class Helper { public static int cube (int num) { return num * num * num; } Because it is declared as static, the method can be invoked as value = Helper.cube(5);

© 2004 Pearson Addison-Wesley. All rights reserved6-36 Static Class Members Static Variables: only one copy of the variable exists (not # of objs) All objects share its static variables Changing the value changes it for all Static methods cannot reference instance variables  Instance variables don't exist until an object exists Static methods can reference static variables or local variables

© 2004 Pearson Addison-Wesley. All rights reserved6-37 Static Class Members Static methods and static variables often work together The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method See SloganCounter.java (page 294)SloganCounter.java See Slogan.java (page 295)Slogan.java

© 2004 Pearson Addison-Wesley. All rights reserved6-38 Class Relationships 1- Dependency: A uses B - A invokes the methods of B  No dependency -> too complex classes  Too much dependency -> Too complex design 2- Aggregation: A has-a B  A references B as instance data 3- Inheritance: A is-a B

© 2004 Pearson Addison-Wesley. All rights reserved6-39 Dependency Some dependencies occur between objects of the same class A method of the class may accept an object of the same class as a parameter For example, the concat method of the String class takes as a parameter another String object str3 = str1.concat(str2); This drives home the idea that the service is being requested from a particular object

© 2004 Pearson Addison-Wesley. All rights reserved6-40 Dependency The following example defines a class called Rational to represent a rational number A rational number is a value that can be represented as the ratio of two integers Some methods of the Rational class accept another Rational object as a parameter See RationalTester.java (page 297)RationalTester.java See RationalNumber.java (page 299)RationalNumber.java

© 2004 Pearson Addison-Wesley. All rights reserved6-41 Aggregation In the following example, a Student object is composed, in part, of Address objects A student has an address (in fact each student has two addresses) See StudentBody.java (page 304)StudentBody.java See Student.java (page 306)Student.java See Address.java (page 307)Address.java An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end

© 2004 Pearson Addison-Wesley. All rights reserved6-42 Object Reference this this in an instance method refers to the corresponding object When method tryMe is called: obj1.tryMe(); obj2.tryMe(); In the first invocation, the this reference refers to obj1; in the second it refers to obj2 Two common usage: 1- to pass the corresponding object as a parameter 2- to access fields shadowed by local variables.

6/11/2016 CS101 - Algorithms & Programming I Passing this as a Parameter public class MyInt { private int ival; public MyInt(int val) { ival=val; } public boolean isGreaterThan(MyInt o2) { return (ival > o2.ival); } public boolean isLessThan(MyInt o2) { return (o2.isGreaterThan(this)); } } in some other place MyInt x1=new MyInt(5), x2=new MyInt(6); x1.isGreaterThan(x2); x1.isLessThan(x2);

© 2004 Pearson Addison-Wesley. All rights reserved Access fields shadowed by local variables Distinguish the instance variables from method parameters with the same names public Account (String name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }

6/11/2016 CS101 - Algorithms & Programming I 45 Methods A method can be:  an instance method (declared without using keyword static ), or  a class method (declared using keyword static, it is also known as a static method). An instance method is associated with an object.  If it accesses an instance variable, it accesses of the copy of that instance variable in the current object. A static method is a class-method and there is only one copy for it.  All instances of that class share that single copy.  A static method cannot access an instance variable or an instance method.

6/11/2016 CS101 - Algorithms & Programming I 46 Overloaded Methods static void m(int x, int y) { System.out.println("m-i-i"); } static void m() { System.out.println("m-noarg"); } static void m(double x, double y) { System.out.println("m-d- d"); } static void m(int x, double y) { System.out.println("m-i- d"); } static void m(double x, int y) { System.out.println("m-d- i"); } static void m(int x) { System.out.println("m-i"); } to invoke this method m(1,2); m(); m(1.1,2.2); m(1,2.2); m(1.1,2); m(1);

© 2004 Pearson Addison-Wesley. All rights reserved6-47 Method Design High-level design:  identifying primary classes and objects  assigning primary responsibilities Low-level: the design of key methods  Make the methods relatively short A public service method may call private support methods

6/11/2016 CS101 - Algorithms & Programming I 48 Recap – Modifiers publicprivateprotected package The class itself yes Classes in the same package yesnoyes Sub-classes in a different package yesnoyesno Non- subclasses in a different package yesno

6/11/2016 CS101 - Algorithms & Programming I 49 Recap - Variables 1.instance variables -- declared in the class (without using static keyword) 2.class variables (static variables) - declared in the class (with using static keyword) 3.local variables – declared in a method or as its formal parameters. An instance method of a class can refer (just using their names) to all instance variables, all static variables declared in the class, and all its local variables. A static method of a class cannot refer to any instance variable declared in that class. It can only refer to static variables and its local variables.

6/11/2016 CS101 - Algorithms & Programming I 50 Variables (cont.) class C { int x; static int y; public void printX() { System.out.println(“x: “+x); } public static void printY() { System.out.println(“y: “+y); } public void m1(int a, int b) { int c=a+b; x=a; y=b; printX(); printY(); } public static m2(int a, int b) { x=a;  ILLEGAL y=b; printX();  ILLEGAL printY(); } }

6/11/2016 CS101 - Algorithms & Programming I 51 Recall - Dot Operator (cont.) class C1 { public int x; public static int y=5; public C1() { x=1; } public void setX(int val) { x=val; } public static void printY() { System.out.println(“y: “ + y); } } // in a method of some other class C1 o1,o2;o1.x = 2; C1.y = 10;o2.x = 3; C1.x = 10;  ILLEGALo1.y = 4; C1.printY();o2.y = 5; C1.setX(10);  ILLEGALC1.y = 6; o1 = new C1(); o1.setX(7); o2 = new C1();o2.setX(8); o1.printY(); o2.printY();