CMSC 202 Classes and Objects: Reusing Classes with Composition.

Slides:



Advertisements
Similar presentations
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Chapter 5 Defining Classes II Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
CS102--Object Oriented Programming
Slides prepared by Rose Williams, Binghamton University Chapter 8 Polymorphism Part I.
CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Review of C++ Programming Part II Sheng-Fang Huang.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
CMSC 202 Classes and Objects: Reusing Classes with Composition.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 8 Operator Overloading, Friends, and References.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
CMSC 202 Inheritance I Class Reuse with Inheritance.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, Stack and Heap When your program is running, some memory is used to store local variables.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
Static Methods Slides 2 to 15 only Static Methods A static method is one that can be used without a calling object A static method still belongs.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
Chapter 5 Defining Classes II
Chapter 5 Defining Classes II
Polymorphism 2nd Lecture
By Pius Nyaanga Momanyi
Classes and Objects 2nd Lecture
CMSC 202 Composition.
Inheritance 2nd Lecture
Classes and Objects Encapsulation
Polymorphism 2nd Lecture
Chapter 5 Defining Classes II
Inheritance 2nd Lecture
CMSC 202 Inheritance.
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
Class Reuse with Inheritance
Chapter 5 Defining Classes II
Inheritance 2nd Lecture
Java Classes and Objects 4th Lecture
Chapter 5 Defining Classes II
Classes, Objects and Methods
Classes and Objects Reusing Classes with Composition
CMSC 202 Inheritance II.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CMSC 202 Classes and Objects: Reusing Classes with Composition

Version 9/092 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 9/093 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 deathday 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 9/094 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 9/095 Designing A Person Class: Instance Variables To support the required services, a simple Person class could contain instance variables representing a person's name, the date on which they were born, and the date on which they died. These instance variables would all be class types: name of type String, and two dates of type Date. As a first line of defense for privacy and to provide proper encapsulation, each of the instance variables would be declared private. public class Person { private String name; private Date born; private Date died; //null means still alive... Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/096 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. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/097 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. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/098 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 9/099 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 ); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0910 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 ); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0911 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 9/0912 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 9/0913 Designing a Person Class: The equals M ethod 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. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0914 Designing a Person Class: The equals Method public boolean equals(Person otherPerson) { if (otherPerson == null) return false; else return name.equals(otherPerson.name) && born.equals(otherPerson.born) && datesMatch(died, otherPerson.died); } Copyright © 2008 Pearson Addison-Wesley All rights reserved This is the equals method for the String class This is the equals method for the Date class This is a special helper method that handles null Date references

Version 9/0915 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 ); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0916 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; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved This is the same as born.toString( )

Version 9/0917 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 9/0918 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; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0919 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? Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0920 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). Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0921 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? Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0922 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. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0923 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 getBirthDate( ) { return born; //dangerous – why?? }  Correct public Date getBirthDate( ) { return new Date( born ); //correct } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0924 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 9/0925 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 9/0926 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 getBornAbbreviation( ) { 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.getBornAbbreviation(); System.out.println( abbrev ); What’s good or bad with this approach?

Version 9/0927 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 9/0928 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? Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0929 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; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0930 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; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/0931 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 9/0932 Remember… “Keep it secret, keep it safe”