Collaborative classes Collaborative classes Robots Learning to - - PowerPoint PPT Presentation
Collaborative classes Collaborative classes Robots Learning to - - PowerPoint PPT Presentation
Collaborative classes Collaborative classes Robots Learning to Program with Java Learning to Program with Java Byron Weber Becker chapter 8 h 8 Announcements (Oct 24) Announcements (Oct 24) Quiz6 Quiz6 Reading for next Monday:
Announcements (Oct 24) Announcements (Oct 24)
- Quiz6
Quiz6
- Reading for next Monday: Ch 9
- Program#6 out today
- Program#6 out today
- Exam#2 scheduled for Nov 9th (Wed 8PM)
- Check program#4 score
- Check program#4 score
Practice Using Class Variables Practice Using Class Variables
Make this static…
Class Variables Class Variables
- Some variables apply across all objects of
Some variables apply across all objects of a class.
- Consider the interest rate on savings
- Consider the interest rate on savings
accounts. C id i i ti id
- Consider assigning consecutive id
numbers to objects.
- Class variables are RARELY needed.
Class Methods Class Methods
- Some methods don’t refer to instance
Some methods don t refer to instance variables.
- They may operate only on class variables
- They may operate only on class variables.
- They may simply operate based on their
t parameters.
- These methods are called by class name
instead of object.
- Write a program that finds the smallest of
Write a program that finds the smallest of several integers. Assume that input will end when a sentinel value of –999 is read end when a sentinel value of 999 is read. Do not count –999 as one of the integers to consider to consider.
Problem 3 Problem 3
- Write a program that sums a sequence of
Write a program that sums a sequence of
- integers. Assume that the first integer
read specifies the number of values read specifies the number of values remaining to be entered. Your program should read only one value at a time A should read only one value at a time. A typical input sequence might be 5 100 200 300 400 500
Problem 4 Problem 4
- Write a program that finds the smallest of
Write a program that finds the smallest of several integers. Assume that input will end when a sentinel value of –999 is read end when a sentinel value of 999 is read. Do not count –999 as one of the integers to consider to consider.
Chapter 8: Objectives Chapter 8: Objectives
- Writing classes that have objects as
Writing classes that have objects as instance variables
- Improved class diagrams
Improved class diagrams
- Understanding reference variables vs
primitive variables primitive variables
- Understanding aliases
- Comparing objects
- Comparing objects
- Exceptions
Consider This Class Diagram Consider This Class Diagram
Person
- String name
- String mother
- String father
- int birthYr
i t bi thMth
- int birthMth
- int birthDay
- int deathYr
- int deathMth
- int deathDay
+Person(String name, String mom, String dad, int bYr, int bMth, int bDay) +int getAge() +String getMother() +String getFather() +String getBirthDate() + id tD thD t (i t dY i t dMth i t dD ) +void setDeathDate(int dYr, int dMth, int dDay) +String toString()
A Date Class A Date Class
- Create a Date class to hold integers to
Create a Date class to hold integers to represent the
day – day – month year – year
- Why not use String data?
Update the Person Class Update the Person Class
Person
- name:String
Date
- int day
- mother:String
- father:String
- dateOfBirth:Date
d t OfD th D t y
- int month
- int year
+ Date(int year, int month, int day)
Has-A 1..2
- dateOfDeath:Date
+ Person(String name, String mom, String dad, int bYr, int bMth, int bDay) + Person(String name, String mom, day) + getYear():int + getMonth():int + getDay():int + getDifference(Date aDate):int String dad, Date birth) + getAge():int + getMother():String + getFather():String + getDifference(Date aDate):int + compareTo(Date aDate):int + equals(Date aDate):boolean + toString():String + getFather():String + getBirthDate():Date + setDeathDate(Date death):void + toString():String
Dates Dates
- Programming dates typically include both
Programming dates typically include both the date and time
- Java provides a number of classes to
- Java provides a number of classes to
handle dates
D t t h i ll d t d 2000 – Date – technically deprecated – pre 2000 – GregorianCalendar
- These and others are somewhat difficult to
use and can be very confusing to new programmers
Problems with the Date Classes Problems with the Date Classes
- All data is stored as integer values
All data is stored as integer values
– Jan is stored as zero, Feb as 1, etc The day of the week is also stored with Sun – The day of the week is also stored with Sun stored as zero, Mon as 1, etc – However the date is stored as 1 – 31 – However, the date is stored as 1 – 31 – In the Date class the year is expected to be entered as a 2 digit year and when stored entered as a 2 digit year and when stored 1900 is added to it. So passing 06 stores 1906 and to store 2006 you must pass 106. y p Passing 2006 results in 3906!
Printing Date Objects Printing Date Objects
- The toString method
The toString method
- A Date object declared as
Date aDate = new Date(59, 5, 30); Date aDate new Date(59, 5, 30); (intending to store May 30,1959) yields Tue Jun 30 00:00:00 CDT 1959
- Using a 4-digit year
Date aDate = new Date(1959, 5, 30); ( ) Tue Jun 30 00:00:00 CDT 3859
- So we must remember to reduce the
month by 1 and pass (59, 4, 30)
Printing GregorianCalendar Printing GregorianCalendar
- The toString method for the GregorianCalendar is used for debugging
purposes only not very useful purposes only – not very useful
- GregorianCalendar gregDate = new GregorianCalendar(1959, 5, 30);
(intending to store May 30,1959) yields java util GregorianCalendar[time=? areFieldsSet=false areAllFieldsSet=fals java.util.GregorianCalendar[time ?,areFieldsSet false,areAllFieldsSet fals e,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset =- 21600000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=j ava.util.SimpleTimeZone[id=America/Chicago,offset=- 21600000 d tS i 3600000 D li ht t t tY 0 t tM d 3 21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3, startMonth=3,startDay=1,startDayOfWeek=1,startTime=7200000,startTime Mode=0,endMode=2,endMonth=9,endDay=- 1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek =1 minimalDaysInFirstWeek=1 ERA=? YEAR=1959 MONTH=5 WEEK OF 1,minimalDaysInFirstWeek 1,ERA ?,YEAR 1959,MONTH 5,WEEK_OF_ YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=30,DAY_OF_YEAR=?, DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=?,HOUR=?,H OUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFS ET=?,DST_OFFSET=?]
Extracting a useful GregorianCalendar date Extracting a useful GregorianCalendar date
- this.gregDate.get(Calendar.YEAR) + "/" +
this gregDate get(Calendar MONTH) + "/" + this.gregDate.get(Calendar.MONTH) + / + this.gregDate.get(Calendar.DAY_OF_MONTH)
- However, we must remember that the month is
- ff by one – so if 5 is stored as the month
- ff by one
so if 5 is stored as the month number, we are talking about June not May
Month Issues Month Issues
- Suppose we want to store Jan 30 so we
Suppose we want to store Jan 30, so we declare a new GregorianCalendar GregorianCalendar gregDate = new GregorianCalendar gregDate new GregorianCalendar(2011, 1, 30);
- We would get this date returned
would actually March 2 2011 would actually March 2, 2011
- Why?
Becker’s DateTime Becker s DateTime
- A Becker class that simplifies both the
A Becker class that simplifies both the Date and GregorianCalendar classes
- Declaring a becker DateTime object as
- Declaring a becker.DateTime object as
DateTime beckerDate = new DateTime(2012, 1, 30);
yields 2012/1/30 yields 2012/1/30 N t ll t h th t th
- Naturally you must have a path to the
becker.jar file and you must use i t b k til D t Ti import becker.util.DateTime;
Improved Class Diagram Improved Class Diagram
becker.DateTime
- year:int
Person
- name:String
- month:int
- day:int
- hours:int
i t i t
Has-A 1 2
- mother:String
- father:String
- dateOfBirth:DateTime
d t OfD th D t Ti
- minutes:int
- seconds:int
+ DateTime() + DateTime(int yr, int mth, int
1 .. 2
- dateOfDeath:DateTime
+ Person(String name, String mom, String dad, DateTime birth) + getAge():int + getMother():String day) + DateTime(int yr, int mth, int day, int hr, int min, int sec) + addYears(int howMany):void + getMother():String + getFather():String + getBirthDate():DateTime + setDeathDate(DateTime death):void + addYears(int howMany):void + addMonths(int howMany):void + addDays(int howMany):void + daysUntil(DateTime date):long + toString():String + equals(Object obj):boolean + toString():String ...
“is a” vs “has a” is a vs has a
- “is a” refers to inheritance relationships
p
– A RobotSE “is a” Robot
- “has a” refers to collaborative classes
– A Person object “has a” DateTime object as an instance variable instance variable
- “has a” relationships can imply several things
– “has exactly one” y – “has at least one” – “has multiple” “ i ht h ” – “might have”
- Composition or cardinality
Consider an Employee Class Consider an Employee Class
- Suppose we create a child class of Person
Suppose we create a child class of Person called Employee
- An Employee object has
- An Employee object has
– A hire date and A l – A salary
Improved Class Diagram Improved Class Diagram
becker.DateTime
- year:int
Person
- name:String
- month:int
- day:int
- hours:int
i t i t
Has-A 1 .. 2
- mother:String
- father:String
- dateOfBirth:DateTime
- dateOfDeath:DateTime
+ P (St i St i St i
- minutes:int
- seconds:int
+ DateTime() + DateTime(int yr, int mth, int
+ Person(String name, String mom, String dad, DateTime birth) + getAge():int + getMother():String + getFather():String + tBi thD t () D t Ti
day) + DateTime(int yr, int mth, int day, int hr, int min, int sec) + addYears(int howMany):void
+ getBirthDate():DateTime + setDeathDate(DateTime death):void + toString():String
is a
+ addYears(int howMany):void + addMonths(int howMany):void + addDays(int howMany):void + daysUntil(DateTime date):long
Employee
- hireDate:DateTime
- salary:double
+ Employee(String name String mom
is a
Has-A 2 .. 3
+ equals(Object obj):boolean + toString():String ...
+ Employee(String name, String mom, String dad, DateTime birthDate, DateTime hiredate) + setSalary(double salary):void + toString():String
Class Diagram (CD) Expectations Class Diagram (CD) Expectations
- A complete class diagram will show all
A complete class diagram will show all relationships
– “is-a”, “has-a”, and “uses-a” relationships
- “has-a” relationships must show cardinality
- All classes used must appear in the CD –
pp including Java classes like NumberFormat
– The String class is commonly used and is included in Java.lang – therefore it does not need to be included in the CD
- The application class is NOT included in a
- The application class is NOT included in a
class diagram
Primitive vs Reference Variables Primitive vs Reference Variables
- Recall Java provides 8 primitive types
Recall, Java provides 8 primitive types
– byte short – short – int long – long – float d bl – double – boolean – char
Primitives Primitives
- Actually hold their value in memory – a
Actually hold their value in memory a direct link
- When passed as parameter values
- When passed as parameter values,
primitives are copied and a copy of their value is passed value is passed
- Therefore inside the method only the copy
i h d t th i i l l is changed, not the original value
Object Storage - References Object Storage References
- Variables declared of some object type (whether
Variables declared of some object type (whether a Java class type – like String, or a user defined class type – like Person) actually store a reference to a memory location where the instance data is stored
- Thus when objects are passed to methods, any
changes made in the method are permanent – changing both the parameter variable and the changing both the parameter variable and the
- riginal variable’s data
- THIS IS VERY IMPORTANT TO
- THIS IS VERY IMPORTANT TO
UNDERSTAND!!!
Object Alaises Object Alaises
- Declaring and instantiating an object
g g j ClassName obj1 = new ClassName ();
- Declaration without instantiation
Cl N bj2 ClassName obj2;
- Object assignment
- bj2 = obj1;
- bj2 = obj1;
- Obj2 = new ClassName(obj1);
copy constructor
Part Class Part Class
- Write a class to hold information about a
Write a class to hold information about a Part
A Part has an ID that contains letters and – A Part has an ID that contains letters and numbers – A Part has a description A Part has a description – A Part has a cost A Part has a quantity on hand – A Part has a quantity on hand – A Part has a quantity on order
Part Methods Part Methods
- When we create a Part we will always assign the
When we create a Part we will always assign the ID, description, cost, and quantity on order
- We might sometimes also create a new Part that
g has current inventory
- We also need to be able to do the following
– Order parts – Receive parts – Sell parts – when we sell parts we should return the total cost of the parts sold
CALTAL CALTAL
- You should always test your methods as
You should always test your methods as you code them.
- Creating a main within the class is an easy
- Creating a main within the class is an easy
way to do that
Additional Methods Additional Methods
- We will want to print Part information to
We will want to print Part information to the screen
We can do this using the toString method – We can do this using the toString method. Typically the toString method is used for one
- f 2 purposes:
p p
- To print the most often needed information
- For debugging printing all data with labels
– If we want to print different information we can create additional methods to do that
toString toString
- Write this method so it returns all Part data
Write this method so it returns all Part data with labels on a single line with tabs between them – in this order between them in this order ID dscrp cost qOnHand qOnOrder
- This way the toString method will typically
- This way the toString method will typically
be used for debugging purposes, showing the current state of the object but not the current state of the object, but not create nice neat columns
Print Method Print Method
- A print method can be used to print just the data (no
l b l ) i t l i i tf labels) in neat columns using printf
- If this is our javadoc for the print method, what would the
code look like
/** * Prints data to System.out on a single line in columns as described * here: * part ID - 10 character column; part ID 10 character column; * description - 15 character column; * cost - 10 character column formatted as currency; * quantity on order - 10 character column; * tit h d 10 h t l * quantity on hand - 10 character column. * * There is a single line return at the end. * */
- NOTE: the description should be left justified
Printing Headers Printing Headers
- We could use the print method to print a
We could use the print method to print a listing of all parts in our system
- Such a listing should have headers
- Such a listing should have headers
- Create a static method to print just the
h d f th li ti headers for the listing
getters and setters getters and setters
- Often we need to get or set information
Often we need to get or set information about the current state of an object.
- Create getters for each data field in the
- Create getters for each data field in the
Part class S fi ld h ld b h d b
- Some fields should never be changed by
the user because of data security
– Create a setter for the price and description
- nly
Equals Method Equals Method
- Must pass a parameter of type Object
Must pass a parameter of type Object
- Must check that the parameter is of the
correct or expected type and return false if correct or expected type and return false if not If t i k
- If type is ok
– Type cast the parameter object to the i t l appropriate class – Check equality data
- Return true or false as appropriate