Object-Oriented Design. Chapter. Class Relationships. Classes in a software system can have various types of relationships to each other

Similar documents
Object-Oriented Design. Chapter

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

Program Development. These activities are not strictly linear they overlap and interact

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 7 Object-Oriented Design

Building Your Own Classes

writing classes objectives chapter

Chapter 5: Writing Classes and Enums

Interfaces. Quick Review of Last Lecture. November 6, Objects instances of classes. Static Class Members. Static Class Members

Interfaces, Testing, and Layout Managers

Software Development Activities. Establishing the requirements. Software Design. CMPT 126: Lecture 8 Object-Oriented Design

CMPT 126: Lecture 8 Object-Oriented Design

Writing Classes Chapter 5. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Review for the. Final Exam. Final Exam. December 8, Final Format. Final Format. Ways to get an A on the Final. A Crash Course in Java

CS1004: Intro to CS in Java, Spring 2005

Anatomy of a Class Encapsulation Anatomy of a Method

ECE 122. Engineering Problem Solving with Java

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Selection Statements and operators

Introduction to Arrays

Selection Statements and operators

Chapter. Let's explore some other fundamental programming concepts

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS101 Class Notes April 25-25, Taygun Murat Yilmaz CHAPTER 6; Static Variables, Class Dependency, Class Aggregation, Interfaces

Chapter 4: Writing Classes

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Programming with Java

Lecture 7: Classes and Objects CS2301

CS 180. Recitation 8 / {30, 31} / 2007

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Language Live! Levels 1 and 2 correlated to the Arizona English Language Proficiency (ELP) Standards, Grades 5 12

Where do objects come from? Good question!

The most common relationships are: dependency, association, generalization, and realization.

Using Classes and Objects

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

COE 212 Engineering Programming. Welcome to Exam II Tuesday November 28, 2018

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Selection and Repetition Revisited

CSC 1051 Data Structures and Algorithms I

ing execution. That way, new results can be computed each time the Class The Scanner

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

2: Basics of Java Programming

Chapter 4 Defining Classes I

Selection and Repetition Revisited

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ June Exam

Design and UML Class Diagrams

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Inheritance and Polymorphism

Java I/O and Control Structures

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Java I/O and Control Structures Algorithms in everyday life

Coding Standards for Java

Problem Grade Total

ECE 122. Engineering Problem Solving with Java

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Oct Decision Structures cont d

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Getting started with Java

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Introduction to Programming Using Java (98-388)

This exam is open book. Each question is worth 3 points.

Supplementary Test 1

Data Structures COE 312 ExamII Preparation Exercises

ASSIGNMENT 3. COMP-202, Winter 2015, All Sections. Due: Tuesday, February 24, 2015 (23:59)

Introduction to Computer Science Unit 2. Notes

Computational Expression

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Computer Science II (20082) Week 1: Review and Inheritance

Introduction to Classes and Objects

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Selection and Repetition

Chapter 7. Arrays are objects that help us organize large amounts of information

Consonant Blends and Digraphs. How to create the Consonant Blends and Digraphs kit

CMPT 125: Lecture 3 Data and Expressions

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

AP CS Unit 3: Control Structures Notes

Solution to Section #3 Portions of this handout by Eric Roberts, Mehran Sahami, Marty Stepp, Patrick Young and Jeremy Keeshin

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Introduction to Computer Science Unit 2. Notes

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Packages & Random and Math Classes

CS 2340 Objects and Design - Scala

Transcription:

Object-Oriented Design 6 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Class Relationships Classes in a software system can have various types of relationships to each other Three of the most common relationships: Dependency: A uses B Aggregation: A has-a B Inheritance: A is-a B Let's discuss dependency and aggregation further Inheritance is discussed in detail in Chapter 8 2007 Pearson Addison-Wesley. All rights reserved 6-2 1

Dependency A dependency exists when one class relies on another in some way, usually by invoking the methods of the other We've seen dependencies in many previous examples We don't want numerous or complex dependencies among classes Nor do we want complex classes that don't depend on others A good design strikes the right balance 2007 Pearson Addison-Wesley. All rights reserved 6-3 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 2007 Pearson Addison-Wesley. All rights reserved 6-4 2

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 302) See RationalNumber.java (page 304) 2007 Pearson Addison-Wesley. All rights reserved 6-5 Aggregation An aggregate is an object that is made up of other objects Therefore aggregation is a has-a relationship A car has a chassis In software, an aggregate object contains references to other objects as instance data The aggregate object is defined in part by the objects that make it up This is a special kind of dependency the aggregate usually relies on the objects that compose it 2007 Pearson Addison-Wesley. All rights reserved 6-6 3

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 309) See Student.java (page 311) See Address.java (page 312) An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end 2007 Pearson Addison-Wesley. All rights reserved 6-7 Aggregation in UML StudentBody + main (args ( : String[]) : void Address - streetaddress : String - city : String - state : String - zipcode : long Student - firstname : String - lastname : String - homeaddress : Address - schooladdress : Address + tostring() : String + tostring() : String 2007 Pearson Addison-Wesley. All rights reserved 6-8 4

StudentBody.java // StudentBody.java Author: Lewis/Loftus // // Demonstrates the use of an aggregate class. public class StudentBody // Creates some Address and Student objects and prints them. public static void main (String[] args) Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jhome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jhome, school); Address mhome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mhome, school); System.out.println (john); System.out.println (); System.out.println (marsha); 2007 Pearson Addison-Wesley. All rights reserved 6-9 Student.java //*********************************************************** // Student.java Author: Lewis/Loftus // // Represents a college student. //********************************************************** public class Student private String firstname, lastname; private Address homeaddress, schooladdress; // Constructor: Sets up this student with the specified values. public Student (String first, String last, Address home, Address school) firstname = first; lastname = last; homeaddress = home; schooladdress = school; //------------------------------------------------- // Returns a string description // of this Student object. //------------------------------------------- public String tostring() String result; result = firstname + " " + lastname + "\n"; result += "Home Address:\n" + homeaddress + "\n"; result += "School Address:\n" + schooladdress; return result; 2007 Pearson Addison-Wesley. All rights reserved 6-10 5

Address.java // Address.java Author: Lewis/Loftus // // Represents a street address. public class Address private String streetaddress, city, state; private long zipcode; // Constructor: Sets up this address with the specified data. public Address (String street, String town, String st, long zip) streetaddress = street; city = town; state = st; zipcode = zip; // Returns a description of this Address object. public String tostring() String result; result = streetaddress + "\n"; result += city + ", " + state + " " + zipcode; return result; 2007 Pearson Addison-Wesley. All rights reserved 6-11 Method Design Again, an algorithm is a step-by-step process for solving a problem Examples: a recipe, travel directions Every method implements an algorithm that determines how the method accomplishes its goals 2007 Pearson Addison-Wesley. All rights reserved 6-16 6

Method Decomposition A method should be relatively small, so that it can be understood as a single entity A potentially large method should be decomposed into several smaller methods as needed for clarity A public service method of an object may call one or more private support methods to help it accomplish its goal Support methods might call other support methods if appropriate 2007 Pearson Addison-Wesley. All rights reserved 6-17 Method Decomposition Let's look at an example that requires method decomposition translating English into Pig Latin Pig Latin is a language in which each word is modified by moving the initial sound of the word to the end and adding "ay" Words that begin with vowels have the "yay" sound added on the end book ookbay table abletay item itemyay chair airchay 2007 Pearson Addison-Wesley. All rights reserved 6-18 7

Method Decomposition The primary objective (translating a sentence) is too complicated for one method to accomplish Therefore we look for natural ways to decompose the solution into pieces Translating a sentence can be decomposed into the process of translating each word The process of translating a word can be separated into translating words that: begin with vowels begin with consonant blends (sh, cr, th, etc.) begin with single consonants 2007 Pearson Addison-Wesley. All rights reserved 6-19 Method Decomposition See PigLatin.java (page 325) See PigLatinTranslator.java (page 327) In a UML class diagram, the visibility of a variable or method can be shown using special characters Public members are preceded by a plus sign Private members are preceded by a minus sign 2007 Pearson Addison-Wesley. All rights reserved 6-20 8

Class Diagram for Pig Latin PigLatin + main (args ( : String[]) : void PigLatinTranslator + translate (sentence : String) : String - translateword (word : String) : String - beginswithvowel (word : String) : boolean - beginswithblend (word : String) : boolean 2007 Pearson Addison-Wesley. All rights reserved 6-21 PigLatin.java // PigLatin.java Author: Lewis/Loftus // // Demonstrates the concept of method decomposition. import java.util.scanner; public class PigLatin // Reads sentences and translates them into Pig Latin. public static void main (String[] args) String sentence, result, another; Scanner scan = new Scanner (System.in); do System.out.println (); System.out.println ("Enter a sentence (no punctuation):"); sentence = scan.nextline(); System.out.println (); result = PigLatinTranslator.translate (sentence); System.out.println ("That sentence in Pig Latin is:"); System.out.println (result); System.out.println (); System.out.print ("Translate another sentence (y/n)? "); another = scan.nextline(); while (another.equalsignorecase("y")); 2007 Pearson Addison-Wesley. All rights reserved 6-22 9

PigLatinTranslator.java // PigLatinTranslator.java Author: Lewis/Loftus // // Represents a translator from English to Pig Latin. Demonstrates // method decomposition. import java.util.scanner; public class PigLatinTranslator // Translates a sentence of words into Pig Latin. public static String translate (String sentence) String result = ""; Scanner scan = new Scanner (sentence); sentence = sentence.tolowercase(); while (scan.hasnext()) result += translateword (scan.next()); result += " "; return result; 2007 Pearson Addison-Wesley. All rights reserved 6-23 PigLatinTranslator.java (cont.) // Translates one word into Pig Latin. If the word begins with a // vowel, the suffix "yay" is appended to the word. Otherwise, // the first letter or two are moved to the end of the word, // and "ay" is appended. private static String translateword (String word) String result = ""; if (beginswithvowel(word)) result = word + "yay"; else if (beginswithblend(word)) result = word.substring(2) + word.substring(0,2) + "ay"; else result = word.substring(1) + word.charat(0) + "ay"; return result; 2007 Pearson Addison-Wesley. All rights reserved 6-24 10

PigLatinTranslator.java (cont.) // Determines if the specified word begins with a vowel. private static boolean beginswithvowel (String word) String vowels = "aeiou"; char letter = word.charat(0); return (vowels.indexof(letter)!= -1); 2007 Pearson Addison-Wesley. All rights reserved 6-25 PigLatinTranslator.java (cont.) // Determines if the specified word begins with a particular // two-character consonant blend. private static boolean beginswithblend (String word) return ( word.startswith ("bl") word.startswith ("sc") word.startswith ("br") word.startswith ("sh") word.startswith ("ch") word.startswith ("sk") word.startswith ("cl") word.startswith ("sl") word.startswith ("cr") word.startswith ("sn") word.startswith ("dr") word.startswith ("sm") word.startswith ("dw") word.startswith ("sp") word.startswith ("fl") word.startswith ("sq") word.startswith ("fr") word.startswith ("st") word.startswith ("gl") word.startswith ("sw") word.startswith ("gr") word.startswith ("th") word.startswith ("kl") word.startswith ("tr") word.startswith ("ph") word.startswith ("tw") word.startswith ("pl") word.startswith ("wh") word.startswith ("pr") word.startswith ("wr") ); 2007 Pearson Addison-Wesley. All rights reserved 6-26 11

Method Overloading Method overloading is the process of giving a single method name multiple definitions If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters 2007 Pearson Addison-Wesley. All rights reserved 6-29 Method Overloading The compiler determines which method is being invoked by analyzing the parameters float tryme(int x) return x +.375; Invocation result = tryme(25, 4.32) float tryme(int x, float y) return x*y; 2007 Pearson Addison-Wesley. All rights reserved 6-30 12

Method Overloading The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total); 2007 Pearson Addison-Wesley. All rights reserved 6-31 Overloading Methods The return type of the method is not part of the signature That is, overloaded methods cannot differ only by their return type Constructors can be overloaded Overloaded constructors provide multiple ways to initialize a new object 2007 Pearson Addison-Wesley. All rights reserved 6-32 13