CMSC 202H. Classes and Objects: Reusing Classes with Composition

Similar documents
Chapter 5. Defining Classes II. Slides prepared by Rose Williams, Binghamton University

Chapter 5. Defining Classes II. Copyright 2016 Pearson Inc. All rights reserved.

CSC 175 Intermediate Programming

Before We Begin. Class Implementation II. Introduction to Computer Science II. Overview (1): Administrative Details (1):

Chapter 4 Defining Classes I

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

APCS Semester #1 Final Exam Practice Problems

CMSC 341 Lecture 7 Lists

Abstract Data Types. Different Views of Data:

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

Aggregation and Composition. [notes Chapter 4]

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

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

Array Based Lists. Collections

JAVA MOCK TEST JAVA MOCK TEST II

Class design guidelines. Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3)

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

CHAPTER 7 OBJECTS AND CLASSES

Chapter 6 Introduction to Defining Classes

Objects and Iterators

Chapter 4. Defining Classes I

CHAPTER 7 OBJECTS AND CLASSES

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

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

Aggregation and Composition. [notes Chapter 4]

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

Comp 249 Programming Methodology

CSC 172 Intermediate Progamming

Based on slides by Prof. Burton Ma

Anatomy of a Class Encapsulation Anatomy of a Method

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Chapter 14. Inheritance. Slide 1

Java Review. Fundamentals of Computer Science

For this section, we will implement a class with only non-static features, that represents a rectangle

JAVA GUI PROGRAMMING REVISION TOUR III

Chapter 4: Writing Classes

Chapter 12 Object-Oriented Programming. Starting Out with Games & Graphics in C++ Tony Gaddis

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

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

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

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

ECE 122. Engineering Problem Solving with Java

CSE 8B Intro to CS: Java

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

Classes Classes 2 / 36

Chapter 4. Defining Classes I

ECOM 2324 COMPUTER PROGRAMMING II

Object Oriented Programming

Data Structures (list, dictionary, tuples, sets, strings)

Classes Classes 2 / 35

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

CIS 190: C/C++ Programming. Classes in C++

BM214E Object Oriented Programming Lecture 8

Mutable and Immutable Objects

Assignment 19 Deadline: Nov pm COSC211 CRN15376 Session 15 (Nov. 7)

Classes and Objects. CGS 3416 Spring 2018

9/17/2018 Programming Data Structures. Encapsulation and Inheritance

Account joeacct = new Account (100, new Account (500)); Account joeacct = new Account (100, new Account (500, null));

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

Introduction to Linked Data Structures

Chapter 14 Inheritance. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Object Oriented Programming

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Course Content. Objectives of Lecture 18 Black box testing and planned debugging. Outline of Lecture 18

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Primitive vs Reference

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Programming II (CS300)

Chief Reader Report on Student Responses:

Chapter 7 Classes & Objects, Part B

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Rules and syntax for inheritance. The boring stuff

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

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

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Equality for Abstract Data Types

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

CS1083 Week 2: Arrays, ArrayList

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

CITS1001 week 4 Grouping objects

Thinking Functionally

Options for User Input

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Programming Exercise 14: Inheritance and Polymorphism

The Singleton Pattern. Design Patterns In Java Bob Tarr

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Chapter 15: Object Oriented Programming

CMSC131. Library Classes

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Garbage Collection (1)

Transcription:

CMSC 202H Classes and Objects: Reusing Classes with Composition

Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing it which is often the case with procedural languages like C. The goal with OOP languages is to reuse classes without changing the code within the class - one OOP technique for code reuse is known as composition. Version 10/11 2

A Simple Database Your favorite cousin wishes to implement a simple database of family relatives. His application has only a few requirements. He would like record the name, birthday, and date of death of each family relative. A report is required that prints all information for each family member. Family members must be comparable to avoid duplicate entries in the database. For ease of data entry, it must be possible to make a copy of an existing family member. Your contribution to this project is to design and implement a class named Person that will represent a single family member. Version 10/11 3

Designing A Person Class: Primitive Instance Variables To model the kinds of entities we will need for the task at hand, a simple Person class would contain instance variables representing details about a person's name, the date on which they were born, and the date on which they died. As a first pass, we could model this data with instance variables of simple types: primitive types and String: public class Person private String name; private int born_date, born_month, born_year; private Date died_date, died_month, died_year;... Also, as a first line of defense for privacy and to provide proper encapsulation, note that we declare each of the instance variables private. 4

Designing A Person Class: Class Instance Variables However, we previously developed a class called Date that would be perfect for storing birth and death dates could we reuse that? Yes, we can, just by including instance variables of class type. (We ve already been doing this with String ). public class Person private String name; private Date born; private Date died; //null means still alive... Again, we should declare each of the instance variables private. 5

Composition Note that the Person class contains three class type instance variables. private String name; private Date born; private Date died; The use of classes as instance variables is a design method known as aggregation or composition. Composition is a fundamental way to reuse code, but there are coding considerations when composition is used. Version 10/11 6

Composition Considerations With composition, Person becomes a user of the Date and String classes. The Person class has no special privileges with respect to Date or String. The Person class should delegate responsibility to the Date and String classes whenever possible. Version 10/11 7

Designing a Person Class: Constraints In order to exist, a person must have (at least) a name and a birth date. Therefore, it would make no sense to have a no-argument Person class constructor. A person who is still alive does not yet have a date of death. Therefore, the Person class constructor will need to be able to deal with a null value for date of death. A person who has died must have had a birth date that preceded his or her date of death. Therefore, when both dates are provided, they will need to be checked for consistency. 8

Designing a Person Class: Behaviors/Services After reading the problem description the following behaviors/services have been identified for the Person class. Create a Person with a name, birthday, and date of death Compare two Person objects to determine if they are identical Format a string containing all Person attributes Create a new Person which is the copy of an existing person Version 10/11 9

Iterative Process As we go into more detail in thinking about the behaviors, we might find other attributes that it would be important, or convenient, to model The process of designing a class is cyclical and evolving in nature Version 10/11 10

Designing a Person Class: The Class Invariant A statement that is always true for every object of the class is called a class invariant. A class invariant can help to define a class in a consistent and organized way. For the Person class, the following should always be true. An object of the class Person has a name, a date of birth (which is not null), and if the object has a date of death, then the date of death is equal to or later than the date of birth Checking the Person class confirms that this is true of every object created by a constructor, and all the other methods (e.g., the private method consistent) preserve the truth of this statement. Version 10/11 11

Class Invariant Summary The class invariant is stated as part of the class documentation. Error checking in the constructor(s) and mutators insure that the class invariant is not violated. Methods of the class which do not change the class state may assume the class invariant holds. Version 10/11 12

A Person Class Constructor public Person( String thename, Date birthdate, Date deathdate ) // check that birthdate <= deathdate // consistent( ) is a private helper method if ( thename!= null && consistent(birthdate, deathdate)) name = thename; born = new Date( birthdate ); // copy the birthedate object if( deathdate == null ) died = null; else died = new Date( deathdate ); else // later we ll deal with errors differently System.out.println( "Inconsistent Person parameters. ); System.exit( 0 ); 13

Designing a Person Class: The Class Invariant /** Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. To be consistent, name and birthdate must not be null. If there is no date of death (deathdate == null), that is consistent with any birthdate. Otherwise, the birthdate must come before or be equal to the deathdate. */ precedes() is a boolean method in Date private boolean consistent(date birthdate, Date deathdate) if( birthdate == null ) return false; if( deathdate == null ) return true; return birthdate.precedes( deathdate ) birthdate.equals( deathdate ); 14

Designing a Person Class: The equals Method The definition of equals for the class Person includes an invocation of equals for the class String, and an invocation of the method equals for the class Date. The Person class passes responsibility for determining equality to the String and Date classes invoking their equals methods. This is an important example of code reuse arising from the use of composition to implement Person. Java determines which equals method is being invoked from the type of its calling object. (Recall: equals() is special, because methods like ArrayList.indexOf() expect to call it.) 15

Designing a Person Class: The equals Method public boolean equals(person otherperson) if (otherperson == null) This is the equals method for the return false; String class else return name.equals(otherperson.name) && born.equals(otherperson.born) && datesmatch(died, otherperson.died); This is the equals method for the Date class This is a special helper method that handles null Date references Copyright 2008 Pearson Addison-Wesley 16

Designing a Person Class: datesmatch Helper Method /** To match date1 and date2 must either be the same date or both be null. */ private boolean datesmatch( Date date1, Date date2 ) if( date1 == null ) return date2 == null; // both null is ok else if( date2 == null ) // && date1!= null return false; // only one null not ok else // both dates are not null return date1.equals( date2 ); 17

Designing a Person Class: The tostring Method The Person class tostring method includes invocations of the Date class tostring method. Again, an example of code reuse and delegation of responsibility due to composition. public String tostring( ) String diedstring; if( died == null ) diedstring = ""; //Empty string else diedstring = died.tostring( ); return name + ", " + born + "-" + diedstring; This is the same as born.tostring( ) 18

Designing a Person Class: Making a Copy Making a copy of an object requires a special method called a copy constructor. A copy constructor is a constructor with a single argument of the same type as the class. The copy constructor should create an object that is a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object. Version 10/11 19

Copy Constructor for a Class with Primitive Type Instance Variables // a class that does not use composition can // simply copy the values of the primitive instance // variables public Date( Date adate ) if( adate == null ) // Not a real date object parameter // we ll handle errors differently later System.out.println( "Fatal Error. ); System.exit( 0 ); // just copy the primitive variables using assignment // month is a String which is NOT primitive, but that s ok month = adate.month; day = adate.day; year = adate.year; 20

Copy Constructor for a Class Using Composition Because of composition, the technique used with Date will not work correctly with Person. public Person( Person original ) if( original == null ) System.out.println( "Fatal error. ); System.exit( 0 ); name = original.name; // ok born = original.born //dangerous died = original.died //dangerous This code would not create an independent copy of the original object. Why not? 21

Copy Constructor for a Class with Class Type Instance Variables The actual copy constructor for the Person class is a "safe" version that creates completely new and independent copies of born and died, and therefore, a completely new and independent copy of the original Person object. For example: born = new Date( original.born ); Note that in order to define a correct copy constructor for a class that uses composition, copy constructors must already be defined for the instance variables' classes (e.g. Date). 22

Copy Constructor for a Class Using Composition public Person( Person original ) if( original == null ) System.out.println( "Fatal error. ); System.exit( 0 ); name = original.name; born = new Date( original.born ); if( original.died == null ) died = null; else died = new Date( original.died ); // Why don t we have to create a new string for name? 23

Using and Misusing References When writing a program, it is very important to insure that private instance variables remain truly private. For a primitive type instance variable, just adding the private modifier to its declaration should insure that there will be no privacy leaks. For a class type instance variable, adding the private modifier alone is not sufficient. 24

Pitfall: Privacy Leaks The previously illustrated examples from the Person class show how an incorrect definition of a copy constructor can result in a privacy leak. A similar problem can occur with incorrectly defined mutator or accessor methods. Wrong public Date getborndate( ) return born; //dangerous why?? Correct public Date getborndate( ) return new Date( born ); //correct 25

Privacy vs. Efficiency As a general rule, privacy considerations trump efficiency in most cases A possible class of exceptions is where the enclosing class is primarily implementing a storage model This is very specific, but also very common E.g.: ArrayLists and other collection classes do not by default do deep copies, and this was by design; you have to manage this yourself if desired If the included class can be considered a part of the state of the enclosing class, it should definitely be completely protected from privacy leaks. E.g.: born instance variable of Person class 26

Composition and Encapsulation Suppose that the user of the Person class has a new requirement: they wish to abbreviate a Person s birth month by displaying only the first 3 characters. How do we provide this feature in an appropriate OOP way keeping in mind the principle of encapsulation? Version 10/11 27

One Way Add an accessor for the born date (getborndate) to the Person class and add an accessor for the month (getmonth) to the Date class. Then the Person class user can write this code. Person bob = new Person( Bob, new Date( January, 14, 1944), null); String abbrev = bob.getborndate( ).getmonth().substring(0,2); System.out.println( abbrev ); What s good or bad with this approach? Version 10/11 28

Another Way Add a new method to the Date class to return the month s abbreviation public String getmonthabbreviation( ) return month.substring(0, 2); Add a new method to the Person class to return the born date abbreviation public String getbornmonthabbreviation( ) return born.getmonthabbreviation(); Now the user of the Person class writes this code. Person bob = new Person( Bob, new Date( January, 14, 1944), null); String abbrev = bob.getbornmonthabbreviation(); System.out.println( abbrev ); What s good or bad with this approach? Version 10/11 29

Composition with Arrays Just as a class type can be used as an instance variable, arrays can also be used as instance variables. We can define an array with a primitive base type. private double[ ] grades; Or, an array with a class base type. private Date [ ] dates; Version 10/11 30

Privacy Leaks with Array Instance Variables If an accessor method is provided for the array special care must be taken just as when an accessor returns a reference to any private object. public double[ ] getgrades( ) return grades; The example above will result in a privacy leak. Why is this so? 31

Privacy Leaks with Array Instance Variables The previous accessor method would simply return a reference to the array grades itself. Instead, an accessor method should return a reference to a deep copy of the private array object. Below, grades is an array which is an instance variable of the class containing the getgrades method. public double[ ] getgrades( ) double[ ] temp = new double[ grades.length ]; for( int i = 0; i < grades.length; i++ ) temp[ i ] = grades[ i ]; return temp; 32

Privacy Leaks with Array Instance Variables If a private instance variable is an array that has a mutable class as its base type, then copies must be made of each class object in the array when the array is copied. public Date[ ] getdates( ) Date[ ] temp = new Date[ dates.length ]; for( int i = 0; i < dates.length; i++ ) temp[ i ] = new Date( dates[ i ] ); return temp; 33

But what if the user really wants to change the array within the class? a. The user shouldn t know that the class uses an array. b. The array must represent some abstract data element in the class (eg student grades). c. Provide a method that changes the the abstract data element without revealing the existence of an array. Version 10/11 34

Remember Keep it secret, keep it safe Version 10/11 35