Lect 09 7 04 13 Chap 3 (cont.) 2/2. Chapter 3 The Importance of Encapsulation Even a simple class can benefit from different implementations Users are.

Slides:



Advertisements
Similar presentations
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Advertisements

CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Chapter Goals To learn how to choose appropriate classes to implement
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Chapter 3 (Horstmann’s Book) Guidelines for Class Design Hwajung Lee.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Chapter 7 – Arrays.
Chapter 7 Designing Classes Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling  To.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Class Design CSC 171 FALL 2004 LECTURE 11. READING Read Chapter 7 It’s abstract But it should help with project #1.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Class design guidelines. 2 Encapsulation Classes can be implemented many different ways –each has advantages & disadvantages –improvement/revision always.
Advanced Object Oriented Programming Chapter 3 & 4.
CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 3: Guidelines for.
More C++ Bryce Boe 2013/07/18 CS24, Summer 2013 C.
18-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Objects and Classes (cont)
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
Week 3 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Week 12 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CSC 142 Computer Science II Zhen Jiang West Chester University
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
CMSC 202 Classes and Objects: Reusing Classes with Composition.
Guidelines for class design Horstmann ch Noter ch.1.1.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CS 151: Object-Oriented Design September 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Chapter 3 Guidelines for Class Design. Objective of this chapter Have “bottom up point of view” Learn how to write a single class well.  The classes.
Midterm 2 Review 1. 2 Object Oriented Programming Write a Date class. It should contain fields for day, month, year, number of months per year, and number.
CMSC 202 Classes and Objects: Reusing Classes with Composition.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
CS 151: Object-Oriented Design September 17 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Chapter 7 Designing Classes. Chapter Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
ITEC324 Principle of CS III
Guidelines for Class Design
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
CMPE 135: Object-Oriented Analysis and Design September 14 Class Meeting Department of Computer Engineering San Jose State University Fall 2017 Instructor:
Chapter 10 Thinking in Objects
Polymorphism 2nd Lecture
Classes and Objects 2nd Lecture
CMSC 202 Composition.
Defining Classes II.
CSC 480 Software Engineering
Chapter 9 Thinking in Objects
Classes and Objects Encapsulation
Polymorphism 2nd Lecture
Java Classes and Objects 3rd Lecture
Chapter 9 Thinking in Objects
Class Everything if Java is in a class. The class has a constructor that creates the object. public class ClassName private Field data (instance variables)
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Chapter 9 Objects and Classes
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
CMPE 135: Object-Oriented Analysis and Design February 21 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor:
Classes and Objects Reusing Classes with Composition
Review for Midterm 3.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Lect Chap 3 (cont.) 2/2

Chapter 3

The Importance of Encapsulation Even a simple class can benefit from different implementations Users are unaware of implementation Public instance variables would have blocked improvement –Can't just use text editor to replace all d.year with d.getYear() –How about d.year++? –d = new Day(d.getDay(), d.getMonth(), d.getYear() + 1) –Ugh--that gets really inefficient in Julian representation Don't use public fields, even for "simple" classes

Accessors and Mutators Mutator: Changes object state Accessor: Reads object state without changing it Day class has no mutators! Class without mutators is immutable String is immutable Date and GregorianCalendar are mutable

Don't Supply a Mutator for every Accessor Day has getYear, getMonth, getDate accessors Day does not have setYear, setMonth,setDate mutators These mutators would not work well –Example: Day deadline = new Day(2001, 1, 31); deadline.setMonth(2); // ERROR deadline.setDate(28); –Maybe we should call setDate first? Day deadline = new Day(2001, 2, 28); deadline.setDate(31); // ERROR deadline.setMonth(3); GregorianCalendar implements confusing rollover. –Silently gets the wrong result instead of error. Immutability is useful

Sharing Mutable References References to immutable objects can be freely shared Don't share mutable references –Example class Employee {... public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDate() { return hireDate; } private String name; private double salary; private Date hireDate; }

Sharing Mutable References Pitfall: Employee harry =...; Date d = harry.getHireDate(); d.setTime(t); // changes Harry's state!!! Remedy: Use clone public Date getHireDate() { return (Date)hireDate.clone(); }

Sharing Mutable References

Final Instance Fields Good idea to mark immutable instance fields as final private final int day; final object reference can still refer to mutating object private final ArrayList elements; elements can't refer to another array list The contents of the array list can change

Separating Accessors and Mutators If we call a method to access an object, we don't expect the object to mutate Rule of thumb: Mutators should return void Example of violation: Scanner in =...; String s = in.next(); Yields current token and advances iteration What if I want to read the current token again?

Separating Accessors and Mutators Better interface: String getCurrent(); void next(); Even more convenient: String getCurrent(); String next(); // returns current Refine rule of thumb: Mutators can return a convenience value, provided there is also an accessor to get the same value

Side Effects Date formatting (basic): SimpleDateFormat formatter =...; String dateString = "January 11, 2012"; Date d = formatter.parse(dateString); Advanced: FieldPosition position =...; Date d = formatter.parse(dateString, position); Side effect: updates position parameter Design could be better: add position to formatter state

Side Effects Avoid modifying static objects Example: System.out Don't print error messages to System.out: if (newMessages.isFull()) System.out.println("Sorry--no space"); Your classes may need to run in an environment without System.out Rule of thumb: Minimize side effects beyond implicit parameter

Constructor 001: public class Day 002: { 003: /** 004: Constructs a day with a given year, month, and day 005: of the Julian/Gregorian calendar. The Julian calendar 006: is used for all days before October 15, 1582 aYear a year != 0 aMonth a month between 1 and 12 aDate a date between 1 and : */ 011: public Day(int aYear, int aMonth, int aDate) 012: { 013: julian = toJulian(aYear, aMonth, aDate); 014: } 015:

016: /** 017: Returns the year of this day the year 019: */ 020: public int getYear() 021: { 022: return fromJulian(julian)[0]; 023: } 024: 025: /** 026: Returns the month of this day the month 028: */ 029: public int getMonth() 030: { 031: return fromJulian(julian)[1]; 032: } 033: 034: /** 035: Returns the day of the month of this day the day of the month 037: */ 038: public int getDate() 039: { 040: return fromJulian(julian)[2]; 041: } 042:

043: /** 044: Returns a day that is a certain number of days away from 045: this day n the number of days, can be negative a day that is n days away from this one 048: */ 049: public Day addDays(int n) 050: { 051: return new Day(julian + n); 052: } 053: 054: /** 055: Returns the number of days between this day and another day. other the other day the number of days that this day is away from 058: the other (>0 if this day comes later) 059: */ 060: public int daysFrom(Day other) 061: { 062: return julian - other.julian; 063: } 064: 065: private Day(int aJulian) 066: { 067: julian = aJulian; 068: } 069:

070: /** 071: Computes the Julian day number of the given day. year a year month a month date a day of the month The Julian day number that begins at noon of 076: the given day 077: Positive year signifies CE, negative year BCE. 078: Remember that the year after 1 BCE was 1 CE. 079: 080: A convenient reference point is that May 23, 1968 noon 081: is Julian day number : 083: Julian day number 0 is a Monday. 084: 085: This algorithm is from Press et al., Numerical Recipes 086: in C, 2nd ed., Cambridge University Press : */ 088: private static int toJulian(int year, int month, int date) 089: { 090: int jy = year; 091: if (year < 0) jy++; 092: int jm = month; 093: if (month > 2) jm++; 094: else 095: { 096: jy--; 097: jm += 13; 098: } 099: int jul = (int) (java.lang.Math.floor( * jy) 100: + java.lang.Math.floor( * jm) + date ); 101: 102: int IGREG = * ( * 1582); 103: // Gregorian Calendar adopted Oct. 15, : 105: if (date + 31 * (month + 12 * year) >= IGREG) 106: // Change over to Gregorian calendar 107: { 108: int ja = (int) (0.01 * jy); 109: jul += 2 - ja + (int) (0.25 * ja); 110: } 111: return jul; 112: } 113:

114: /** 115: Converts a Julian day number to a calendar date. 116: 117: This algorithm is from Press et al., Numerical Recipes 118: in C, 2nd ed., Cambridge University Press : j the Julian day number an array whose 0 entry is the year, 1 the month, 122: and 2 the day of the month. 123: */ 124: private static int[] fromJulian(int j) 125: { 126: int ja = j; 128: int JGREG = ; 129: // The Julian day number of the adoption of the Gregorian calendar 131: if (j >= JGREG) 132: // Cross-over to Gregorian Calendar produces this correction 133: { 134: int jalpha = (int) (((float) (j ) ) 135: / ); 136: ja += 1 + jalpha - (int) (0.25 * jalpha); 137: } 138: int jb = ja ; 139: int jc = (int) ( ((float) (jb ) ) 140: / ); 141: int jd = (int) (365 * jc + (0.25 * jc)); 142: int je = (int) ((jb - jd) / ); 143: int date = jb - jd - (int) ( * je); 144: int month = je - 1; 145: if (month > 12) month -= 12; 146: int year = jc ; 147: if (month > 2) --year; 148: if (year <= 0) --year; 149: return new int[] { year, month, date }; 150: } 151: 152: private int julian; 153: }