6. object-oriented design based on java software development, 5 th ed. by lewis &loftus

47
6. Object- 6. Object- Oriented Design Oriented Design Based on Based on Java Software Development, 5 Java Software Development, 5 th th Ed. Ed. By Lewis &Loftus By Lewis &Loftus

Upload: alfred-matthews

Post on 04-Jan-2016

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

6. Object-6. Object-Oriented DesignOriented Design

Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.

By Lewis &LoftusBy Lewis &Loftus

Page 2: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 3: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Software Development Software Development StepsSteps

Analyze and Establish RequirementsAnalyze and Establish Requirements What are needed? Not, how to do them.What are needed? Not, how to do them.

Develop Software DesignDevelop Software Design How to accomplish goals; How to divide How to accomplish goals; How to divide

the solution; What classes are needed?the solution; What classes are needed? Implement ProgramsImplement Programs

Coding, using programming language(s)Coding, using programming language(s) Test ProgramsTest Programs

Debug logic error; check against Debug logic error; check against requirements; test usablilityrequirements; test usablility

Page 4: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 5: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Identifying Classes & Identifying Classes & ObjectsObjects

Object-Oriented DesignObject-Oriented Design What kind of objects are involved in the What kind of objects are involved in the

problem?problem? Start with Start with nounsnouns in the problem in the problem

description description

Page 6: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Identifying Classes & Identifying Classes & ObjectsObjects

A partial requirements document:A partial requirements document:

Of course, not all nouns will correspond to Of course, not all nouns will correspond to class objects in the final solution.class objects in the final solution.

The user must be allowed to specify each product byits primary characteristics, including its name andproduct number. If the bar code does not match theproduct, then an error should be generated to themessage window and entered into the error log. Thesummary report of all transactions must be structuredas specified in section 7.A.

Page 7: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Possible ClassesPossible Classes

User User Product (Product (name, productNumber)name, productNumber) BarCodeBarCode (value, productNumber) (value, productNumber) MessageWindow (MessageWindow (message)message) ErrorLog (ErrorLog (date, time, message)date, time, message) SummaryReport (SummaryReport (date, header, date, header,

message)message) Transactions (Transactions (date, date,

transactionType, amount)transactionType, amount)

Page 8: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Identifying Classes & Identifying Classes & ObjectsObjects

Remember, a class represents a group Remember, a class represents a group (classification) of objects with similar (classification) of objects with similar characteristicscharacteristics and and behaviorsbehaviors..

Generally, use a singular for class Generally, use a singular for class name: name: StudentStudent, , ReportReport, , WindowWindow, , BankAccountBankAccount..

Once a class is defined, many objects Once a class is defined, many objects of that class can be of that class can be instantiatedinstantiated..

Page 9: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Identifying Classes & Identifying Classes & ObjectsObjects

Sometimes, question arises: Should a Sometimes, question arises: Should a name become a name become a classclass or or attributeattribute??

E.g.: Should E.g.: Should addressaddress be represented by a be represented by a set of instance variables in the set of instance variables in the StudentStudent class, or as an object of class, or as an object of AddressAddress class? class?

Ordinarily, address should be attribute. Ordinarily, address should be attribute. But sometimes, it may be worth making it But sometimes, it may be worth making it a class. The decision depends on the a class. The decision depends on the amount of detail required by the solutionamount of detail required by the solution

Page 10: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Identifying Classes & Identifying Classes & ObjectsObjects

Part of identifying the classes is Part of identifying the classes is assigning assigning responsibilitiesresponsibilities to each class. Which class to each class. Which class does what?does what?

Every action in the program must be Every action in the program must be represented by a method assigned to one represented by a method assigned to one of the classes.of the classes.

In the beginning of the design, In the beginning of the design, verbsverbs in in the problem description give hints on the problem description give hints on identifying identifying methodsmethods..

E.g., …”generate report” suggests that the E.g., …”generate report” suggests that the class class ReportReport should have a method should have a method “generate.”“generate.”

Page 11: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 12: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static Class MembersStatic Class Members

Static MethodStatic Method Is invoked with the class name, not object Is invoked with the class name, not object

name. E.g., name. E.g., result = Math.sqrt(11).result = Math.sqrt(11). Static VariableStatic Variable

Single value for the entire class, unlike Single value for the entire class, unlike instance variablesinstance variables

Important design considerationImportant design consideration Static Methods and VariablesStatic Methods and Variables

Also calledAlso called class method class method && class variable class variable Use modifierUse modifier static static

Page 13: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static VariableStatic Variable Each object has its own variable space: E.g., Each object has its own variable space: E.g.,

class Student {class Student { String name; String name; int age; int age; … …}}

Static variable is common to all objects:Static variable is common to all objects:

class Student {class Student { String name; String name; int age; int age; public static int count; // count of public static int count; // count of // students // students … …}}

Page 14: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static Variable (cont.)Static Variable (cont.) Static variable is common to all objects:Static variable is common to all objects:

class Student {class Student { private String name; private String name; private int age; private int age; private static int count; // count of private static int count; // count of // students // students … …

// Constructor // Constructor Student(String aName, int anAge){Student(String aName, int anAge){ name = aName; name = aName; age = anAge; age = anAge; count++ count++ } }

Page 15: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static Variable (cont.)Static Variable (cont.) public void setName(String aName){public void setName(String aName){ … … } }

public String getName(){public String getName(){ … … } }

//Static method //Static method public static int getCount()(public static int getCount()(

return count; return count; } }

public String toString(){ public String toString(){ … … } }

}}

Page 16: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Invoking Static MethodInvoking Static Method class TestStudent {class TestStudent { Student john = new Student(“John”, 21); Student john = new Student(“John”, 21); Student mary = new Student(“Mary”, 20); Student mary = new Student(“Mary”, 20);

System.out.println(john.getName()); System.out.println(john.getName()); System.out.println(mary); System.out.println(mary); System.out.println(Student System.out.println(Student..getCount() + getCount() + “ students were created.”); “ students were created.”);

Page 17: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static MethodStatic Method class Helper {class Helper { public static int cube (int num) public static int cube (int num) { { return num * num * num; return num * num * num; } }}}

Because it is declared as static, the Because it is declared as static, the method can be invoked asmethod can be invoked as

intint value = Helper.cube(5);value = Helper.cube(5);

Page 18: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Static Class MembersStatic Class Members By convention, By convention, visibilityvisibility modifier comes modifier comes

first, then first, then staticstatic modifier. modifier. Recall, method Recall, method main()main() is a static method— is a static method—

invoked by the Java interpreter without an invoked by the Java interpreter without an object instantiation.object instantiation.

Static method can reference static Static method can reference static variables.variables.

Static method cannot reference instance Static method cannot reference instance variables—because they do not exist until variables—because they do not exist until an object is created.an object is created.

Example ProgramExample Program SloganCounter.java Slogan.java

Page 19: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 20: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Class RelationshipClass Relationship

Classes in a software system can Classes in a software system can have different types of relationship.have different types of relationship. Dependency: A uses BDependency: A uses B Aggregation: A has-a BAggregation: A has-a B Inheritance: A is-a BInheritance: A is-a B

Page 21: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

DependencyDependency class Address {class Address {

private String streetNum: private String streetNum: private String city; private String city; private String state; private String state; private String zip; private String zip; … …}}

class Student {class Student { private String name; private String name; private Address homeAddress; private Address homeAddress; private Address dormAddress; private Address dormAddress; … …}}

Page 22: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

DependencyDependency Class A depends on class B when objects of Class A depends on class B when objects of

class A relies on the services of objects of class A relies on the services of objects of class B; e.g., by invoking methods of class class B; e.g., by invoking methods of class B.B.

This is reusability of code. Instead of This is reusability of code. Instead of writing a complex code in class A, make writing a complex code in class A, make use of what’s in class B.use of what’s in class B.

On the other hand, we don’t want to have On the other hand, we don’t want to have class A depend on too many classes so class A depend on too many classes so that it becomes too complex.that it becomes too complex.

We need a balance in design.We need a balance in design.

Page 23: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

DependencyDependency

Some dependencies occur between Some dependencies occur between objects of the same class.objects of the same class.

Fraction f1, f2, sum;Fraction f1, f2, sum;……sum = f1.add(f2);sum = f1.add(f2);

RationalTester.java RationalNumber.java

Page 24: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

AggregationAggregation

An An aggregateaggregate is an object which is is an object which is made up of objects of other classes.made up of objects of other classes.

CarCar has the following parts: has the following parts:chassis, engine, transmission, chassis, engine, transmission, electricSystem, fuelSystem, etc.electricSystem, fuelSystem, etc.

Car Car has-ahas-a Chassis, Engine, Chassis, Engine, Transmission, etc.Transmission, etc.

An aggregate object contains objects An aggregate object contains objects of other classes as instance variables.of other classes as instance variables.

Page 25: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

AggregationAggregation class Engine {class Engine {

private in size; private in size; private String type; private String type; private int pistons; private int pistons; … …}}

class Transmission {class Transmission { private String type; private String type; private int gears; private int gears; … …}}

class Car {class Car { private Engine engine; private Engine engine; private Transmission transmission; private Transmission transmission; private Chasis chasis; private Chasis chasis; … …} }

Page 26: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Example ProgramExample Program

StudentBody.javaStudentBody.java Student.javaStudent.java Address.javaAddress.java

Page 27: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Aggregation in UMLAggregation in UML

StudentBody

+ main (args : String[]) : void

+ toString() : String

Student- firstName : String- lastName : String- homeAddress : Address- schoolAddress : Address

+ toString() : String

- streetAddress : String- city : String- state : String- zipCode : long

Address

String

Page 28: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

thisthis Reference Reference Inside a class object, this reference refers Inside a class object, this reference refers

to itself.to itself. class Student {class Student { private String name; private String name; private int age; private int age; … … Student (String name, int age) { Student (String name, int age) { this.name = name; this.name = name; this.age = age; this.age = age; } } … …

Page 29: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

InterfaceInterface

We have used “interface” in several We have used “interface” in several contexts—GUI, set of public elements contexts—GUI, set of public elements in a class, i.e., what the user sees.in a class, i.e., what the user sees.

In Java, In Java, interfaceinterface has a special has a special meaning.meaning.

InterfaceInterface Collection of constants and abstract Collection of constants and abstract

methods (no implementation)methods (no implementation) Like a class, but has no instance Like a class, but has no instance

variablesvariables

Page 30: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

InterfaceInterface

Abstract MethodAbstract Method Has method header, but no bodyHas method header, but no body This means that that the user of an This means that that the user of an

abstract method must provide an abstract method must provide an explicit implementation.explicit implementation.

Interface provides a list of methods Interface provides a list of methods that can be used by multiply users, that can be used by multiply users, each providing different each providing different implementation.implementation.

Page 31: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

InterfaceInterface

An interface contains only method An interface contains only method headers.headers.

public interface Doable{ public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

Page 32: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

InterfaceInterface

An interface cannot be instantiated.An interface cannot be instantiated. Methods in an interface have Methods in an interface have publicpublic

visibility by defaul.visibility by defaul. A class that uses an interface must A class that uses an interface must

implement implement allall its abstract methods. its abstract methods.

Page 33: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

InterfaceInterface Class CanDo implements Doable {Class CanDo implements Doable { public DoThis { public DoThis { // whatever // whatever } }

public DoThat { public DoThat { // whatever // whatever } } … …}}

implementsimplements is a reserved word. is a reserved word.

Page 34: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Example ProgramsExample Programs

Complexity.javaComplexity.java Question.javaQuestion.java MiniQuiz.javaMiniQuiz.java Java Standard Class Library (Java API) Java Standard Class Library (Java API)

contains many interfaces. E.g.,contains many interfaces. E.g., ComparableComparable IteratorIterator

Page 35: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 36: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Method DesignMethod Design

A method should be small enough to A method should be small enough to be understood easily (what it does)be understood easily (what it does)

A complex method should invoke A complex method should invoke support methods (from the same support methods (from the same class) or other methods (from other class) or other methods (from other classes).classes).

Page 37: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

PigLatinTranslaterPigLatinTranslater

Pig Latin is a language whereby each Pig Latin is a language whereby each English word is modified by moving English word is modified by moving the initial letter of the word to the the initial letter of the word to the end and adding "ay“. (e.g., book end and adding "ay“. (e.g., book ookbay)ookbay)

Words that begin with vowels have Words that begin with vowels have the "yay" sound added on the end.the "yay" sound added on the end.

Page 38: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Pig Latin TranslaterPig Latin Translater

Words that begin with vowels have the Words that begin with vowels have the "yay" sound added on the end."yay" sound added on the end.

bookbook ookbayookbay tabletable abletayabletayitemitem itemyayitemyay chairchair airchayairchaytree tree reetay chicken reetay chicken ickenchay ickenchay

Pig Latin 101Pig Latin 101

Page 39: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

PigLatin TranslaterPigLatin Translater

Primary MethodPrimary Method String translate(String sentence)String translate(String sentence) This is complicatedThis is complicated

Decompose methodDecompose method

result result “” “”Repeat to end of sentenceRepeat to end of sentence word word getNextWord(sentence)getNextWord(sentence) result result result + result + translateWord(word)translateWord(word)End repeatEnd repeat

Page 40: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

translateWord() MethodtranslateWord() Methodprivate static String translateWord(String word)private static String translateWord(String word){{ String result = "";String result = "";

if (if (beginsWithVowel(word)beginsWithVowel(word))) result = word + "yay";result = word + "yay"; else if (else if (beginsWithBlend(word)beginsWithBlend(word))) result = word.substring(2) result = word.substring(2) + word.substring(0,2) + "ay"; + word.substring(0,2) + "ay"; elseelse result = word.substring(1) + word.charAt(0) + "ay";result = word.substring(1) + word.charAt(0) + "ay";

return result;return result;

}}

Consonant Blend: ch, th, sp, etc.Consonant Blend: ch, th, sp, etc.

Page 41: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

beginsWithVowel() beginsWithVowel() MethodMethod

private static boolean beginsWithVowel private static boolean beginsWithVowel (String word)(String word){{ String vowels = "aeiou";String vowels = "aeiou"; char letter = word.charAt(0);char letter = word.charAt(0); return (vowels.indexOf(letter) != -1);return (vowels.indexOf(letter) != -1);}}

PigLatin.javaPigLatin.java

PigLatinTranslater.javaPigLatinTranslater.java

Page 42: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Method OverloadingMethod Overloading

Method OverloadingMethod Overloading Using same name for two or more Using same name for two or more

methods which have different definitionsmethods which have different definitions Signature of a MethodSignature of a Method

Consists of the number, types, and order Consists of the number, types, and order of parametersof parameters

A calling statement can distinguish A calling statement can distinguish two overloaded methods if they have two overloaded methods if they have different signatures.different signatures.

Page 43: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Method OverloadingMethod Overloading The compiler determines which The compiler determines which

method is invoked by analyzing its method is invoked by analyzing its parameter list.parameter list.

float tryMe(int x){ return x + .375;}

float tryMe(int x, float y){ return x*y;}

result = tryMe(25, 4.32)

Invocation

Page 44: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

Method OverloadingMethod Overloading

System.out.println() is overloadedSystem.out.println() is overloaded println(“Hello”);println(“Hello”); // String // Stringprintln(5);println(5); // int // intprintln(2.32);println(2.32); // float // float

Constructors are often overloaded.Constructors are often overloaded. Provides multiple ways of initializing an object. Provides multiple ways of initializing an object.

E.g.,E.g., Student = new Student(); Student = new Student(); Student = new Student(“John”, 23, “m”);Student = new Student(“John”, 23, “m”);Student = new Student(“John”);Student = new Student(“John”);

Page 45: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 46: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout

Page 47: 6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus

TopicsTopicsSoftware Development Activities

Identifying Classes and Objects

Static Variables and Methods

Class Relationships

Interfaces

Enumerated Types Revisited

Method Design

Testing

GUI Design and Layout