Docsity

Comparison of Reference and Primitive Variables in Java: Examples and Diagrams, Study notes of Computer Science

Partial preview of the text

Download Comparison of Reference and Primitive Variables in Java: Examples and Diagrams and more Study notes Computer Science in PDF only on Docsity!

Java:Learning to Program with RobotsChapter 08: Collaborative Classes

Chapter Objectives

After studying this chapter, you should be able to:

Write a class that uses references to an object with instancevariables, parameter variables, and temporary variables

Draw class diagrams depicting collaborating classes

Explain how reference variables are different from primitivevariables

Explain what an alias is and what dangers arise from aliasing

Write code that compares two objects for equivalence

Throw and catch exceptions

Use a Java collection object to collaborate with many objects, allhaving the same type

8.1.2: Multiple Classes to Model a Person

This class already exists in the

becker

library. A small test program: import becker.util.DateTime;public class DateTest{

public static void main(…){^

// October 1, 1990 DateTime lukesBD =

new DateTime(1990, 10, 1);

// The data and time given by the computer’s clock. DateTime today = new DateTime();int daysOld = lukesBD.daysUntil(today);System.out.println(

"Luke is “

  • daysOld +

" days old."

DateTime

-int year-int month-int day+DateTime( )+DateTime(int yr, int mth, int day)+DateTime(DateTime dateToCopy)+void addYears(int howM any)+void addM onths(int howM any)+void addDays(int howM any)+int daysUntil(DateTime d)+boolean equals(Object obj)+String format( )+int getYear( )+int getM onth( )+int getDay( )+boolean isAfter(DateTime d)+boolean isBefore(DateTime d)+void setFormatInclude(int what)+void setFormatLength(int len)+String toString( )

8.1.2: Reimplementing the Person Class (1/2)

import becker.util.Test;import becker.util.DateTime; public class Person extends Object{ private String name;

// person's name

private String mother;

// person's mother's name

private String father;

// person's father's name

private DateTime birth;

// birth date

private DateTime death;

// death date (null if still alive)

/** Construct a new person. */ public Person(String aName, String mom, String dad,

DateTime birthDate, DateTime deathDate)

{ super();

this.name = aName;this.mother = mom;this.father = dad; this.birth = birthDate;this.death = deathDate; }

Instance variables

Initialize instance variables

Parameter variables

8.1.2: Null Values

Assigning the special value

null

to a variable means it does not refer to

any object.A variable can be compared for equality to

null

if (this.death == null){ …

if (this.death != null){ …

The

,^

,^

, and

operators don’t work.

Calling a method when a variable contains

null

results in an exception:

public class Person extends Object{ private DateTime death = null;

…public int daysSinceDeath(){ DateTime today = new DateTime();

return this.death.daysUntil(today); } } Exception in thread “main” java.lang.NullPointerException

at Person.daysSinceDeath(Person.java:53)at Person.main(Person.java:75)

8.1.3: Diagramming Collaborating Classes

Two different ways for classes to collaborate;Two different ways to diagram them

Person

-String name-String mother-String father-DateTime birth-DateTime death+Person(String aName,

String dad, String mom,int bYear, int bM onth,int bDay)

+int getAge( )+String getFather( )+String getM other( )+String getName( )+void setDeathDate(int dYear,

int dM onth, int dDay)

DateTime

-int year-int month-int day+DateTime( )+DateTime(int yr, int mth, int day)+void addYears(int howM any)+void addM onths(int howM any)+void addDays(int howM any)+long daysUntil(DateTime d)+boolean equals(Object obj)+int getYear( )+int getM onth( )+int getDay( )+boolean isAfter(DateTime d)+boolean isBefore(DateTime d)+String toString( )

1..

Superclass

attributesmethods

Subclass

attributesmethods

8.2: Reference Variables

import becker.util.DateTime;public class Main extends Object{ public static void main(String[ ] args)

DateTime lukesBD = new DateTime(1990, 10, 1);DateTime today = new DateTime();int daysOld = lukesBD.daysUntil(today);System.out.println(

"Luke is "

  • daysOld +

" days old."

} These variables are often represented this way. Why?

daysOld

DateTime

year: 1990 month: 10

day: 1

lukesBD

8.2.1: Memory

51025103

(daysOld) 5104

510551065107510851095110

12 101605009

127 -

0 0 0 0

5102

(lukesBD) 5103

5104 10159

(year) 10160 (month) 10161

(day) 10162

10163

12 101605009

-19 199010 (^120)

A computer’s memory:

like a long series of boxes, each with an address and holding avalue; addresses are numbered consecutively

a variable (

daysOld

,^

lukesBD

) is a name for an address in memory

for primitive variables (

int

), it’s the address of the value

for reference variables (

lukesBD

), it’s the address of the

address

8.2.2: Aliases

The following code:

DateTime lukesBD = new DateTime(1990, 10, 1);DateTime annasBD = lukesBD;

results in this situation:

DateTime

year 1990 month 10

day 1

lukesBD

annasBD

lukesBD.addYear(1);annasBD.addYear(2); results in the

year

instance variable being 1993!

8.2.2: Aliases

The situation is similar with parameters. DateTime lukesBD = new DateTime(1990, 10, 1);this.doSomething(lukesBD);…public void doSomething(DateTime d){ …

DateTime

year 1990 month 10

day 1

lukesBD

d

8.2.4: Testing for Equality

DateTime lukesBD = new DateTime(1990, 10, 1);DateTime annasBD = new DateTime(1990, 10, 1);DateTime today = new DateTime();int lukesAge = lukesBD.daysUntil(today);int annasAge = annasBD.daysUntil(today);if (lukesAge == annasAge){^

// what to do if Luke and Anna are the same age … if (lukesBD == annasBD){^

// what to do if Luke and Ann have the same birth date …

DateTime year: 1990 month: 10

date: 1

DateTime year: 1990 month: 10

date: 1

annasBDlukesBD

DateTime year: 1990 month: 10

date: 1

annasBDlukesBD

Returns

true

Returns

false

Why?

8.2.4 A Method to Test Equivalence

public class DateTime extends Object{ private int year;

private int month;private int day;… /** Test if this date/time object means the same date/time as the other DateTime object. */ public boolean isEquivalent(DateTime other){ return other != null &&

this.year == other.getYear() &&this.month == other.getMonth() &&this.day == other.getDay();

} /** Another way to do it. */ public boolean isEquivalent(DateTime other){ return other != null &&

this.year == other.year &&this.month == other.month &&this.day == other.day;

Case Study: IVoteCounter Interface (1/2)

import becker.util.IView; /** Objects implementing this interface can count the votes in an election.* * @author Byron Weber Becker */ public interface IVoteCounter{^

/** Add a candidate for the election.* @param name The candidate's name* @param pixFile A gif or jpg of the candidate, if available / public void addCandidate(String name, String pixFile); /* Get the number of candidates registered with this vote counter. / public int getNumCandidates(); /* Get the name of the give candidate.* @param candidateNum The number (0..getNumCandidates()-1) of the candidate whose*^

name is desired. */

public String getName(int candidateNum); /** Get the picture file name of the give candidate.* @param candidateNum The number (0..getNumCandidates()-1) of the candidate whose*^

pixfile is desired. */

public String getPixFile(int candidateNum);

Case Study: IVoteCounter Interface (2/2)

/** Add one vote for the named candidate, provided the vote has not yet closed..* @param candidateNum The number (0..getNumCandidates()-1) of the candidate that*^

received the vote. */

public void addVote(int candidateNum); /** Get the number of votes for the named candidate, but only if the election has closed.* @param candidateName The name of a candidate* @return The number of votes received by the candidate; -1 if voting has not yet closed. / public int getVotes(int candidateNum); /* Stop accepting votes for this election. / public void closeElection(); /* Is the election closed? / public boolean isClosed(); /* Add a view to this model.* @param aView The view to add. */ public void addView(IView aView); }