Designing Classes. Appendix D. Slides by Steve Armstrong LeTourneau University Longview, TX 2007, Prentice Hall

Similar documents
This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

JAVA OBJECT-ORIENTED PROGRAMMING

Bags. Chapter 1. Copyright 2012 by Pearson Education, Inc. All rights reserved

Chapter 4 Defining Classes I

Assertions, pre/postconditions

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

CS1004: Intro to CS in Java, Spring 2005

Anatomy of a Class Encapsulation Anatomy of a Method

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

public static boolean isoutside(int min, int max, int value)

Programming II (CS300)

Intermediate Programming

Chapter 4: Writing Classes

MechEng SE3 Lecture 7 Domain Modelling

Assignment 1 due Monday at 11:59pm

Defining Classes and Methods

ITI 1120 Lab #9. Slides by: Diana Inkpen, Alan Williams, Daniel Amyot Some original material by Romelia Plesa

Chapter 1: Principles of Programming and Software Engineering

Goals of the Lecture OO Programming Principles

Interfaces. James Brucker

James Newkirk

UMBC CMSC 331 Final Exam

public static void negate2(list<integer> t)

Object Orientated Analysis and Design. Benjamin Kenwright

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Objects and Classes Lecture 2

Inheritance and Polymorphism

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

INTERNATIONAL EDITION. Problem Solving with C++ Data Abstraction & SIXTH EDITION. Walls and Mirrors. Frank M. Carrano Timothy Henry

JAVA CONCEPTS Early Objects

CPS122 Lecture: Detailed Design and Implementation

OBJECT ORİENTATİON ENCAPSULATİON

TeenCoder : Java Programming (ISBN )

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

Chapter 10 Object-Oriented Design Principles

What is Inheritance?

CS 1316 Exam 1 Summer 2009

Objects First with Java

Introduction to Programming Using Java (98-388)

Programming Exercise 14: Inheritance and Polymorphism

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

Defining Classes and Methods

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

Java Object Oriented Design. CSC207 Fall 2014

CompuScholar, Inc. 9th - 12th grades

Object Oriented Programming with Java

CSCI 200 Lab 1 Implementing and Testing Simple ADTs in Java

Java Classes, Inheritance, and Interfaces

Chapter 15: Object Oriented Programming

Can you think of a situation where this would occur?

CST141 Thinking in Objects Page 1

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

CSE331 Winter 2014, Midterm Examination February 12, 2014

Programming II (CS300)

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Distributed Systems Recitation 1. Tamim Jabban

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Polymorphism and Inheritance

Programming II (CS300)

Introduction to Inheritance

Solutions to the 2005 exam

Programming II (CS300)

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

CS-202 Introduction to Object Oriented Programming

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

5. Defining Classes and Methods

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

COMP Information Hiding and Encapsulation. Yi Hong June 03, 2015

Chapter 1: Programming Principles

Super-Classes and sub-classes

CSE wi Midterm Exam 2/8/18. Name UW ID #

Chapter 5 Object-Oriented Programming

Documentation Requirements Computer Science 2334 Spring 2016

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Session 04 - Object-Oriented Programming 1 Self-Assessment

There are three basic elements in object oriented programming: encapsulation, inheritance and polymorphism.

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

25. Generic Programming

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)

IMACS: AP Computer Science A

Recommended Group Brainstorm (NO computers during this time)

CS2210 Data Structures and Algorithms

Chapter Goals. Chapter 7 Designing Classes. Discovering Classes Actors (end in -er, -or) objects do some kinds of work for you: Discovering Classes

Absolute C++ Walter Savitch

Chapter 11 Classes Continued

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

VALLIAMMAI ENGINEERING COLLEGE

Object-Oriented Systems Analysis and Design Using UML

Class diagrams and architectural design

Unified Modeling Language (UML)

Programming II (CS300)

Classes, interfaces, & documentation. Review of basic building blocks

Review sheet for Final Exam (List of objectives for this course)

Test 1: CPS 100. Owen Astrachan. October 1, 2004

CIS 265/506 Exam1 Spring 2012 Prof. V. Matos Exam Last Name First Name:

Transcription:

Designing Classes Appendix D Slides by Steve Armstrong LeTourneau University Longview, TX 2007, Prentice Hall

Chapter Contents Encapsulation Specifying Methods Java Interfaces Writing an Interface Implementing an Interface An Interface as a Data Type Generic Types Within an Interface Type Casts Within an Interface Implementation Extending an Interface Interfaces Versus Abstract Classes Named Constants Within an Interface

Chapter Contents Choosing Classes Identifying Classes CRC Cards The Unified Modeling Language Reusing Classes

Encapsulation Hides the fine detail of the inner workings of the class The implementation is hidden Often called "information hiding" Part of the class is visible The necessary controls for the class are left visible The class interface is made visible The programmer is given only enough information to use the class

Encapsulation Fig. 3-1 An automobile's controls are visible to the driver, but its inner workings are hidden.

Abstraction A process that has the designer ask what instead of why What is it you want to do with the data What will be done to the data The designer does not consider how the class's methods will accomplish their goals The client interface is the what The implementation is the how

Abstraction Fig. 3-2 An interface provides well-regulated communication between a hidden implementation and a client.

Question 1 How does a client interface differ from a class implementation? Question 2 Think of an example, other than an automobile, that illustrates encapsulation. What part of your example corresponds to a client interface and what part to an implementation?

1. A client interface describes how to use the class. It contains the headers for the class s public methods, the comments that tell you how to use these methods, and any publicly defined constants of the class. The implementation consists of all data fields and the definitions of all methods, including those that are public, private, and protected. 2. A television is one example. The remote control and the controls on the TV form the client interface. The implementation is inside the TV itself.

Specifying Methods Specify what each method does Precondition Defines responsibility of client code Postcondition Specifies what will happen if the preconditions are met

Specifying Methods Responsibility Precondition implies responsibility for guarantee of meeting certain conditions Where to place responsibility Client? or Method? Best to comment this clearly before method's header Also good to have method check during debugging

Question 3 Assume that the class Square has a data field side and the method setside to set the value of side. What header and comments can you write for this method? Keep in mind a precondition and postcondition as you do this.

3. Here are three possibilities: /** Sets the side of the square to a new value. @param newside a real number >= 0 */ public void setside(double newside) /** Sets the side of the square to a new value. @param newside a real number @return true if the side is set, or false if newside is < 0 */ public boolean setside(double newside) /** Sets the side of the square to a new value. @param newside a real number @throws IllegalArgumentException if newside is < 0 */ public void setside(double newside)

Assertions Assertion is statement of truth about aspect of a program's logic Like a boolean statement that should be true at a certain point Assertions can be written as comments to identify design logic // Assertion: intval >= 0

Question 4 Suppose that you have an array of positive integers. The following statements find the largest integer in the array. What assertion can you write as a comment after the for loop? int max = 0; for (int index = 0; index < array.length; index++) { if (array[index] > max) max = array[index]; } // Assertion:

4. // Assertion: max is the largest of array[0],..., array[index]

Assert Statement assert someval < 0; if true, program does nothing If false, program execution terminates Exception in thread main java.lang.assertionerror assert sum > 0 : sum; Or adds the value of sum to the error message in case sum 0. assert sum > 0 : "sum greater than zero"; By default, assert statements are disabled at execution time.

Java Interface A program component that contains Public constants Signatures for public methods Comments that describe them Begins like a class definition Use the word interface instead of class

Writing an Interface Consider geometric figures which have both a perimeter and an area We want classes of such objects to have such methods And we want standardization signatures View example of the interface Measurable

Java Interface Example Recall class Name from previous chapter Consider an interface for the class Name View example listing Note Comments of method purpose, parameters, pre- and post-conditions Any data fields should be public, final, and static Interface methods cannot be final

Implementing an Interface A class that implements an interface must state so at start of definition with implements clause The class must implement every method declared in the interface Multiple classes can implement the same interface A class can implement more than one interface

Implementing an Interface Fig. 3-3 The files for an interface, a class that implements the interface, and the client.

Question 5 Write a Java interface that specifies and declares methods for a class of students. Question 6 Begin the definition of a class that implements the interface that you wrote in answer to the previous questions. Include data fields, a constructor, and at least one method definition.

5. public interface StudentInterface { public void setstudent(name studentname, String studentid); public void setname(name studentname); public Name getname(); public void setid(string studentid); public String getid(); public String tostring(); } // end StudentInterface

6. public class Student implements StudentInterface { private Name fullname; private String id; // identification number public Student() { fullname = new Name(); id = ""; } // end default constructor public Student(Name studentname, String studentid) { fullname = studentname; id =studentid; } // end constructor public void setstudent(name studentname, String studentid) { setname(studentname); // or fullname = studentname; setid(studentid); // or id = studentid; } // end setstudent

An Interface as a Data Type An interface can be used as a data type or

Question 7 What revision(s) should you make to both the interface you wrote for Question 5 and the class Student that implements it to make use of NameInterface?

7. In the interface and in the class, replace Name with NameInterface in the methods setstudent, setname, and getname. Additionally in the class, replace Name with NameInterface in the declaration of the data field fullname and in the parameterized constructor.

Generic Types Within an Interface Recall class OrderedPair Note the setpair method Consider an interface Pairable that declares this method A class that implements this interface could begin with the statement

The Interface Comparable Method compareto compares two objects, say x and y Returns signed integer Returns negative if x < y Returns zero if x == y Returns positive if x > y

The Interface Comparable Consider a class Circle Methods equals, compareto Methods from Measurable View source code Note Implements Measurable interface Shown with two alternative versions of compareto

Question 8 Define a class Name that implements the interface NameInterface, as given in Listing D-2, and the interface Comparable.

8. /** A class that represents a person's name. @author Frank M. Carrano */ public class Name implements NameInterface, Comparable<Name> { private String first; // first name private String last; // last name public Name() { first = ""; last = ""; } // end default constructor public Name(String firstname, String lastname) { first = firstname; last = lastname; } // end constructor public void setname(string firstname, String lastname) { setfirst(firstname); setlast(lastname); } // end setname public String getname() { return tostring(); } // end getname public void setfirst(string firstname) { first = firstname; } // end setfirst public String getfirst() { return first; } // end getfirst public void setlast(string lastname) { last = lastname; } // end setlast

public String getlast() { return last; } // end getlast public void givelastnameto(nameinterface aname) { aname.setlast(last); } // end givelastnameto public String tostring() { return first + " " + last; } // end tostring public int compareto(name other) { int result = last.compareto(other.last); // if last names are equal, check first names if (result == 0) result = first.compareto(other.first); return result; } // end compareto } // end class Name

Extending an Interface Use inheritance to derive an interface from another When an interface extends another It has all the methods of the inherited interface Also include some new methods Also possible to combine several interfaces into a new interface Not possible with classes

Question 9 Imagine a class Pet that contains the method setname, yet does not implement the interface Nameable of Segment D.24. Could you pass an instance of Pet as the argument of the method with the following header? void entershow(nameable petname)

9. No. The class Pet must state that it implements Nameable in an implements clause.

Interfaces Versus Abstract Classes Purpose of interface similar to purpose of abstract class But an interface is not a base class It is not a class of any kind Use an abstract base class when You need a method or private data field that classes will have in common Otherwise use an interface

Named Constants Within an Interface An interface can contain named constants Public data fields initialized and declared as final Consider an interface with a collection of named constants Then derive variety of interfaces that can make use of these constants

Choosing Classes Look at a prospective system from a functional point of view Ask What or who will use the system What can each actor do with the system Which scenarios involve common goals Use a case diagram

Choosing Classes Fig. 3-4 A use case diagram for a registration system

Identifying Classes Describe the system Identify nouns and verbs Nouns suggest classes Students Transactions Customers Verbs suggest appropriate methods Print an object Post a transaction Bill the customer

Identifying Classes Fig. 3-5 A description of a use case for adding a course

CRC Cards Index cards each card represents one class Write a descriptive name for class at top List the class's responsibilities The methods Indicate interactions The collaborations These are CRC cards "Class-Responsibility-Collaboration"

CRC Cards Fig. 3-6 A class-responsibility-collaboration card

Question 10 Write a CRC card for the class Student given in Appendix C.

10

Unified Modeling Language Used to illustrate a system's classes and relationships Provides a class diagram Class name Attributes Operations Fig. 3-7 A class representation that can be part of a class diagram.

Unified Modeling Language Fig. 3-8 UML notation for a base class Student and two derived classes

Question 11 How would the class Name, given in Appendix B, appear in a class diagram of the UML?

Unified Modeling Language Fig. 3-9 A class diagram showing the base class Student and two derived classes

Unified Modeling Language Fig. 3-10 Part of a UML class diagram with associations.

Question 12 Combine previous 2 slides into one class diagram. Then add a class AllCourses that represents all courses offered this semester. What new association(s) do you need to add?

12. Add a unidirectional association (arrow) from AllCourses to Course with a cardinality of 1 on its tail and * on its head.

Reusing Classes Much software combines: Existing components New components When designing new classes Plan for reusability in the future Make objects as general as possible Avoid dependencies that restrict later use by another programmer