Problem Solving #1 Problem Solving #1 ICS201-071 ICS201-071
Dec 19, 2015
Problem Solving #1Problem Solving #1
ICS201-071ICS201-071
22
Outline Outline
Review of Key TopicsReview of Key Topics Example ProgramExample Program
– Problem 7.1Problem 7.1 Problem Solving Tips Problem Solving Tips
33
Review of Main TopicsReview of Main Topics
Creating subclasses: Creating subclasses: – ““is-a” relationship is-a” relationship – why & howwhy & how– What is inherited What is inherited
Using Using this this referencereference Using Using supersuper reference reference Derived class constructors Derived class constructors Overriding methods Overriding methods
– Overriding versus overloadingOverriding versus overloading The The finalfinal modifier modifier The access (visibility) modifiers: The access (visibility) modifiers: publicpublic, , privateprivate, ,
protectedprotected, and default, and default Class hierarchies & UML class diagramsClass hierarchies & UML class diagrams
Form Groups of 3 Students Form Groups of 3 Students and Work on the Following and Work on the Following ProblemProblem
55
Problem 7.1Problem 7.1
a) Define a class named Payment that a) Define a class named Payment that contains contains – a member variable of type double that a member variable of type double that
stores the amount of the payment and stores the amount of the payment and appropriate accessor and mutator methods. appropriate accessor and mutator methods.
– a method named paymentDetails that a method named paymentDetails that outputs an English sentence that describes outputs an English sentence that describes the amount of the payment. the amount of the payment.
66
SolutionSolution
1.1. class Paymentclass Payment2.2. {{3.3. private double amount;private double amount;4.4. public Payment(){public Payment(){ {{5.5. amount = 0;amount = 0;6.6. }}7.7. public Payment(double amount){public Payment(double amount){8.8. this.amount = amount;this.amount = amount;9.9. }}10.10. public void setPayment(double amount){public void setPayment(double amount){11.11. this.amount = amount;this.amount = amount;12.12. }}13.13. public double getPayment(){public double getPayment(){14.14. return amount;return amount;15.15. }}16.16. public void paymentDetails(){public void paymentDetails(){17.17. System.out.println("The payment amount is " + amount);System.out.println("The payment amount is " + amount);18.18. }}19.19. }}
77
Problem 7.1 …Problem 7.1 …
b) Define a class named b) Define a class named CashPayment that is derived from CashPayment that is derived from Payment. Payment. – This class should redefine the This class should redefine the
paymentDetails method to indicate paymentDetails method to indicate that the payment is in cash. Include that the payment is in cash. Include appropriate constructor(s). appropriate constructor(s).
88
SolutionSolution
1.1. class CashPayment extends Payment{class CashPayment extends Payment{2.2. public CashPayment(){public CashPayment(){3.3. super();super();4.4. }}5.5. public CashPayment(double amt){public CashPayment(double amt){6.6. super(amt);super(amt);7.7. }}8.8. public void paymentDetails(){public void paymentDetails(){9.9. System.out.println("The cash payment amount System.out.println("The cash payment amount
is " is " 10.10. + getPayment());+ getPayment());11.11. }}12.12. }}
99
Problem 7.1 …Problem 7.1 …
c) Define a class named c) Define a class named CreditCardPayment that is derived CreditCardPayment that is derived from Payment. from Payment. – This class should contain member This class should contain member
variables for the name on the card, variables for the name on the card, expiration date, and credit card number. expiration date, and credit card number. Include appropriate constructor(s). Include appropriate constructor(s).
– redefine the paymentDetails method to redefine the paymentDetails method to include all credit card information in the include all credit card information in the printout. printout.
1010
SolutionSolution
1.1. class CreditCardPayment extends Payment{class CreditCardPayment extends Payment{2.2. private String name;private String name;3.3. private String expiration;private String expiration;4.4. private String creditcard;private String creditcard;5.5. public CreditCardPayment(){public CreditCardPayment(){6.6. super();super();7.7. name = "";name = "";8.8. expiration = "";expiration = "";9.9. creditcard = "";creditcard = "";10.10. }}11.11. public CreditCardPayment(double amt, String name, String expiration, String creditcard){public CreditCardPayment(double amt, String name, String expiration, String creditcard){12.12. super(amt);super(amt);13.13. this.name = name;this.name = name;14.14. this.expiration = expiration;this.expiration = expiration;15.15. this.creditcard = creditcard;this.creditcard = creditcard;16.16. }}17.17. public void paymentDetails(){public void paymentDetails(){18.18. System.out.println("The credit card payment amount is " + getPayment());System.out.println("The credit card payment amount is " + getPayment());19.19. System.out.println("The name on the card is: " + name);System.out.println("The name on the card is: " + name);20.20. System.out.println("The expiration date is: " + expiration);System.out.println("The expiration date is: " + expiration);21.21. System.out.println("The credit card number is: " + creditcard);System.out.println("The credit card number is: " + creditcard);22.22. }}23.23. }}
1111
Problem 7.1 …Problem 7.1 …
d) Define a test class having a main d) Define a test class having a main method that creates at least two method that creates at least two CashPayment and two CashPayment and two CreditCardPayment objects with CreditCardPayment objects with different values and calls different values and calls paymentDetails for each. paymentDetails for each.
1212
SolutionSolution
1.1. class Question1Payment{class Question1Payment{2.2. public static void main(String[] args)public static void main(String[] args)3.3. {{4.4. CashPayment cash1 = new CashPayment(50.5), cash2 = new CashPayment(20.45);CashPayment cash1 = new CashPayment(50.5), cash2 = new CashPayment(20.45);5.5. CreditCardPayment credit1 = new CreditCardPayment(10.5, "Fred", "10/5/2010", CreditCardPayment credit1 = new CreditCardPayment(10.5, "Fred", "10/5/2010",
"123456789");"123456789");6.6. CreditCardPayment credit2 = new CreditCardPayment(100, "Barney", "11/15/2009", CreditCardPayment credit2 = new CreditCardPayment(100, "Barney", "11/15/2009",
"987654321");"987654321");7.7. System.out.println("Cash 1 details:");System.out.println("Cash 1 details:");8.8. cash1.paymentDetails();cash1.paymentDetails();9.9. System.out.println();System.out.println();10.10. System.out.println("Cash 2 details:");System.out.println("Cash 2 details:");11.11. cash2.paymentDetails();cash2.paymentDetails();12.12. System.out.println();System.out.println();13.13. System.out.println("Credit 1 details:");System.out.println("Credit 1 details:");14.14. credit1.paymentDetails();credit1.paymentDetails();15.15. System.out.println();System.out.println();16.16. System.out.println("Credit 2 details:");System.out.println("Credit 2 details:");17.17. credit2.paymentDetails();credit2.paymentDetails();18.18. System.out.println();System.out.println();19.19. }}20.20. }}
1313
Problem SolvingProblem Solving
The purpose of writing a program is to solve a The purpose of writing a program is to solve a problemproblem
For large problems, we need a systematic way for For large problems, we need a systematic way for software developmentsoftware development
Software development process Software development process – Problem solving phaseProblem solving phase– Implementation phaseImplementation phase– Testing & debugging phaseTesting & debugging phase– Deployment & upgrading phaseDeployment & upgrading phase
Problem solving should provide a solution without Problem solving should provide a solution without being distracted by programming language syntaxbeing distracted by programming language syntax
The general steps in problem solving are:The general steps in problem solving are:– Analyze and understand the problemAnalyze and understand the problem– Design a solution to the problemDesign a solution to the problem– Analyze the complexity of the algorithmAnalyze the complexity of the algorithm– Consider alternatives to the solution and refine itConsider alternatives to the solution and refine it
1414
Design methodologiesDesign methodologies
Object oriented design (OOD)Object oriented design (OOD)– A technique used for developing software in which A technique used for developing software in which
the solution is expressed in terms of objects (i.e. the solution is expressed in terms of objects (i.e. entities composed of data and operations on that entities composed of data and operations on that data and interact by exchanging messages)data and interact by exchanging messages)
Focus is on objects and their interactionFocus is on objects and their interaction Procedural designProcedural design
– A technique for developing software in which the A technique for developing software in which the problem is divided into more easily subproblems, problem is divided into more easily subproblems, their solutions create a solution for the overall their solutions create a solution for the overall problemproblem
Focus is on procedures or functionsFocus is on procedures or functions
1515
Object-Oriented Object-Oriented DesignDesign Discover classes Determine responsibilities of each
class Describe relationships between
the classes
1616
Discovering ClassesDiscovering Classes
A class represents some useful concept Concrete entities: bank accounts,
ellipses, and products Abstract concepts: streams and
windows Find classes by looking for nouns in the
task description Define the behavior for each class Find methods by looking for verbs in
the task description
1717
Discovering Classes …Discovering Classes …
Example: Example: InvoiceInvoice
1818
Discovering Classes …Discovering Classes …
Brainstorm: Simply keep a list of candidate classes
Filter: Determine which are the useful classes in the problem and cross out others
Keep the following points in mind: – Class represents set of objects with the same
behavior Entities with multiple occurrences in problem
description are good candidates for objects Find out what they have in common Design classes to capture commonalities
– Not all classes can be discovered in analysis phase – Represent some entities as objects, others as
primitive types Should we make a class Address or use a String?
1919
ExampleExample
Brainstorming and filteringBrainstorming and filtering– Circling the nouns and underlining the Circling the nouns and underlining the
verbsverbs
Example …Example …
First pass at a list of classesFirst pass at a list of classes
Example …Example …
Filtered listFiltered list
2222
Discovering Classes: Discovering Classes: Another ExampleAnother Example Analyze classes
Invoice Address LineItem // Records the product and the quantity Product Description // Field of the Product class Price // Field of the Product class Quantity // Not an attribute of a Product Total // Computed – not stored anywhere Amount Due // Computed – not stored anywhere
Classes after a process of elimination
Invoice Address LineItem Product
Invoice Address LineItem Product
Description Price
Quantity Total
Amount Due
2323
CRC CardsCRC Cards
Describes a class, its responsibilities, and its collaborators
Use an index card for each class Pick the class that should be responsible for each
method (verb) Write the responsibility onto the class card Indicate what other classes are needed to fulfill
responsibility (collaborators)
2424
CRC CardsCRC Cards
2525
Relationships Between Relationships Between ClassesClasses Inheritance (A Inheritance (A is-ais-a B) B) Aggregation (A Aggregation (A has-ahas-a B) B) Dependency (A Dependency (A usesuses B) B)
2626
Relationships Between Relationships Between Classes: ExampleClasses: Example
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
Later we will explain more about aggregation and dependancyLater we will explain more about aggregation and dependancy
2727
Inheritance Inheritance Relationship: Example Relationship: Example 11
2828
Inheritance Inheritance Relationship: Example Relationship: Example 22 Example 2Example 2
2929
Method DesignMethod Design
As we've discussed, high-level design issues As we've discussed, high-level design issues include:include:
– identifying primary classes and objectsidentifying primary classes and objects
– assigning primary responsibilitiesassigning primary responsibilities
After establishing high-level design issues, its After establishing high-level design issues, its important to address low-level issues such as important to address low-level issues such as the design of key methodsthe design of key methods
For some methods, careful planning is For some methods, careful planning is needed to make sure they contribute to an needed to make sure they contribute to an efficient and elegant system designefficient and elegant system design
3030
Method Design …Method Design …
An An algorithmalgorithm is a step-by-step process for is a step-by-step process for solving a problemsolving a problem
Examples: a recipe, travel directionsExamples: a recipe, travel directions
Every method implements an algorithm that Every method implements an algorithm that determines how the method accomplishes its determines how the method accomplishes its goalsgoals
An algorithm may be expressed in An algorithm may be expressed in pseudocodepseudocode, a mixture of code statements , a mixture of code statements and English that communicate the steps to and English that communicate the steps to taketake
3131
Method Design …Method Design …
A method should be relatively small, so that A method should be relatively small, so that it can be understood as a single entityit can be understood as a single entity
A potentially large method should be A potentially large method should be decomposed into several smaller methods as decomposed into several smaller methods as needed for clarityneeded for clarity
A public service method of an object may call A public service method of an object may call one or more private support methods to help one or more private support methods to help it accomplish its goalit accomplish its goal
Support methods might call other support Support methods might call other support methods if appropriatemethods if appropriate