184
1 Intro to Computer Science I Chapter 4 Classes, Objects, and Methods OOP Concepts

Intro to Computer Science I

  • Upload
    muriel

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

Intro to Computer Science I. Chapter 4 Classes, Objects, and Methods OOP Concepts. Strings (1). A String is a sequence of 0 or more characters Every string has a length associated with it An empty string has length 0 - PowerPoint PPT Presentation

Citation preview

Page 1: Intro to Computer Science I

1

Intro to Computer Science I

Chapter 4Classes, Objects, and Methods

OOP Concepts

Page 2: Intro to Computer Science I

2BGA

Strings (1)

A String is a sequence of 0 or more characters

Every string has a length associated with it

An empty string has length 0 Each character is stored internally as a

16-bit Unicode character (16-bit integer) Each character in a string has an index

associated with it.

Page 3: Intro to Computer Science I

3BGA

Strings (2)

Literal string: sequence of 0 or more characters delimited by double quote characters

Example: "Hello" Empty string: "" Memory model:

H e l l o

0 1 2 3 4

index begins at 0

The double quotesare not part of the string

Page 4: Intro to Computer Science I

4BGA

Substring

A substring is constructed by specifying a subsequence of characters

H e l l o

0 1 2 3 4

e l l

0 1 2

A substring is a string

Page 5: Intro to Computer Science I

5BGA

Constructing a literal string

Strings are objects String greeting = "Hello World";

Hello World

Stringgreeting

object referencevariable

object reference

object

Page 6: Intro to Computer Science I

6BGA

String expressions

Strings can be concatenated together Numeric values can be automatically

converted to strings The + sign is used to denote addition

and also string concatenation RULE: In a + b if one of a or b is a

string then the other will be converted to a string if necessary

Page 7: Intro to Computer Science I

7BGA

String expression examples

String first = "William";String middle = "James";String last = "Duncan";String fullName = first + " " + middle + " " + last;

fullname has the value "William James Duncan"

Page 8: Intro to Computer Science I

8BGA

Mixed string expressions (1)

String area = "Area: " + Math.sqrt(2.0);

The value of area is"Area: 1.4142135623730951"

You can try this in BeanShell and use print(area); to see the result

Page 9: Intro to Computer Science I

9BGA

Mixed string expressions (2)

"The sum of " + x + " and " +y + " is " + x + y

if x is 3 and y is 4 then the result of this expression is"The sum of 3 and 4 is 34"

What's wrong?

Page 10: Intro to Computer Science I

10BGA

Length of a string

Prototype: int length()

Example:

String name = "Harry";int len = name.length();

The value of lenwill be 5

Page 11: Intro to Computer Science I

11BGA

Number to string conversion

Examples

String s1 = "" + age;String s2 = "" + area;

If age is 34 and area is 2.34 then s1 and s2 will have the

values "34" and "2.34"

Page 12: Intro to Computer Science I

12BGA

Extracting characters

Prototype: char charAt(int index)

Example

String s = "Hello";char c = s.charAt(1);

Here the value of c is 'e'(index begins at 0)

Page 13: Intro to Computer Science I

13BGA

Substring construction

Prototypes String substring(int firstIndex) String substring(int firstIndex, int lastIndexPlusOne)

int d = 531452;String sd = "" + d;int len = sd.length();sd = "$" + sd.substring(0,len-3) + "," + sd.substring(len-3);

result is"$531,452"

Page 14: Intro to Computer Science I

14BGA

Trimming spaces

Prototype String trim()

String s = " Hello ";s = s.trim();

result is"Hello"

Page 15: Intro to Computer Science I

15BGA

String case conversion

upper/lower case conversion Prototypes

String toLowerCase() String toUpperCase()

String test = "Hello";String upper = test.toUpperCase();String lower = test.toLowerCase();char first = test.toLowerCase().charAt(0);

results are "HELLO", "hello" and "h"

Page 16: Intro to Computer Science I

16BGA

String search methods

Searching for one string inside another Prototypes

int indexOf(char ch) int indexOf(char ch, int startIndex) int indexOf(String sub) int indexOf(String sub, int startIndex)

Method Overloading: these methods all have the same name but

they have different signatures

signature

Page 17: Intro to Computer Science I

17BGA

String search examples

String target = "This is the target string";

target.indexOf('u')

target.indexOf("the")

target.indexOf("target",13)

value is -1

value is 8

value is -1

Page 18: Intro to Computer Science I

18BGA

Displaying numbers, strings

Some prototypes: void print(int n) void print(double d) void print(String s) void println(int n) void println(double d) void println(String s) void println()

print but don'tmove to next line

print and moveto next line

Output appears in the terminal window

Page 19: Intro to Computer Science I

19BGA

Examples:

double area = 3.14159;System.out.println("Area: " + area);

double area = 3.14159;System.out.print("Area: ");System.out.println(area);

These produce the same results

Page 20: Intro to Computer Science I

20BGA

Examples:

System.out.println("Hello");

System.out.print("Hello\n");

These produce the same results since \n is interpreted as the newlinecharacter

\ is called the escape

character

Page 21: Intro to Computer Science I

21BGA

Examples:

System.out.println("\"\\Hello\\\"");

Displayed result is"\Hello\"

Page 22: Intro to Computer Science I

22BGA

The BlueJ terminal window

public void display(){ System.out.println("Radius = " + radius); System.out.println("Area = " + area); System.out.println("...");}

put this method inCircleCalculator

class

Page 23: Intro to Computer Science I

23BGA

The toString method

Prototype public String toString()

Purpose return a string representation of an object

Default representation toString is special: every class has a

default toString method with a string representation that is not very useful so we normally provide our own version of this method.

Page 24: Intro to Computer Science I

24BGA

Default toString example

bsh % addClassPath("c:/book-projects/chapter3");bsh % CircleCalculator circle = new CircleCalculator(3.0);bsh % String rep = "toString gives " + circle;bsh % print(rep);toString gives CircleCalculator@4d1d41bsh % rep = "toString gives " + circle.toString();bsh % print(rep);toString gives CircleCalculator@4d1d41bsh % print(circle);CircleCalculator@4d1d41

Using the object name circle in a string expression isequvalent to using circle.toString()

Not verymeaningful

Page 25: Intro to Computer Science I

25BGA

Define our own toString

public String toString(){ return "CircleCalculator[radius=" + radius + ", area=" + area + ", circumference=" + "]";}

add this methodto CircleCalculator cass

print(circle);CircleCalculator[radius=3.0, area=28.274333882308138,circumference=18.84955592153876]

now the displayed result is meaningful

Page 26: Intro to Computer Science I

26BGA

Why toString ?

It is useful to write a toString method for every class. The toString representation of an object obj can be displayed using System.out.println(obj);

This is useful for debugging classes (finding logical errors) since it provides an easy way to display the state of any object.

Page 27: Intro to Computer Science I

27BGA

Formatting data (Java 5)

public static String format(String f, Object... args)

The String class contains a static method with prototype

Here f is the format string and Object... args represents theargument list of values to be formatted.

There is also a new printf method that can be used with aformat string that has the prototype

public void printf(String f, Object... args)

Page 28: Intro to Computer Science I

28BGA

Format codes (Java 5)Format codes begin with %Here are some useful ones (see javadoc for complete list)

%5d format an integer right justified in field of width 5%-5d format at integer left justified in a field of width 5%-20s format s string left justified in a field of width 20%15.5f format a floating point number right justified in a field

of width 15 using fixed format rounded to 5 digits afterthe decimal point

%.5f format a floating point nuber in a field that just fitsusing fixed format rounded to 5 digits after the decimalpoint

%20.8e format a floating point number right justified in a fieldof width 20 using exponential (scientific) formatrounded to 8 digits after the decimal point

Page 29: Intro to Computer Science I

29BGA

Format example (1)

The statements

int i = 3;double pi = Math.PI;String end = "End";String f = String.format("answer: %5d%15.5f%10s\n", i, pi, end);System.out.println(f);

produce the output

answer: 3 3.14159 End

%5d %15.5f %10s

Page 30: Intro to Computer Science I

30BGA

Format example (2)

The statements

int i = 3;double pi = Math.PI;String end = "End";System.out.printf("answer: %5d%15.5f%10s\n", I, pi, end);

produce the same output using printf

answer: 3 3.14159 End

%5d %15.5f %10s

To reuse formats use the format method in the String class

Page 31: Intro to Computer Science I

31BGA

Format example(3)

In the CircleCalculator class we could include the followingdisplay method that formats the results.

public void display(){ System.out.printf("Radius = %.5f\n", radius); System.out.printf("Area = %.5f\n", area); System.out.printf("Circumference = %.5f\n", circumference);}

to display the values rounded to 5 digits after the decimal pointin fields that just fit.

Page 32: Intro to Computer Science I

32

Intro to Computer Science I

Chapter 4Example classes that use the

String class

Page 33: Intro to Computer Science I

33BGA

Design, Implement, Test

Begin with an English description of a class

Design the class by deciding what constructors and methods it should have. This is called writing the public specification

or public interface. Write the complete class by providing the

implementation Test the class by itself using BlueJ

Page 34: Intro to Computer Science I

34BGA

BankAccount class description

A BankAccount object should represent a bank account using an account number, an owner name, and a current balance.

There should be a constructor for creating a bank account given these values.

There should be methods to withdraw or deposit a given amount and the usual "get methods" for retrurning the account number, owner name, and balance.

Page 35: Intro to Computer Science I

35BGA

BankAccount class design

public class BankAccount{ // instance data fields go here

public BankAccount(int accountNumber, String ownerName, double initialBalance) {...} public void deposit(double amount) {...} public void withdraw(double amount) {...} public int getNumber() {...} public String getOwner() {...} public double getBalance() {...} public String toString() {...}}

Page 36: Intro to Computer Science I

36BGA

How will we use the class

BankAccount account = new BankAccount(123, "Fred", 125.50);

account.withdraw(100);

System.out.println("Balance is " + account.getBalance());

Construct an object

withdraw $100

display balance

Page 37: Intro to Computer Science I

37BGA

formal and actual arguments

BankAccount myAccount = new BankAccount(123, "Fred", 125.50);

public BankAccount(int accountNumber, String ownerName, double initialBalance) { ...}

Actual arguments in constructor call expression

Formal arguments in constructor prototype

Same idea applies to method call expressions and prototypes

Page 38: Intro to Computer Science I

38BGA

Implementing the class (1)

instance data fields

private int number;private String name;private double balance;

Page 39: Intro to Computer Science I

39BGA

Implementing the class (2)

constructor implementation

public BankAccount(int accountNumber, String ownerName, double initialBalance){ number = accountNumber; name = ownerName; balance = initialBalance;}

Page 40: Intro to Computer Science I

40BGA

Implementing the class (3)

deposit, withdraw (mutator methods)

public void deposit(double amount){ balance = balance + amount;}

public void withdraw(double amount){ balance = balance - amount;}

Page 41: Intro to Computer Science I

41BGA

Implementing the class (4)

get methods (enquiry methods)

public int getNumber(){ return number;}

public String getName(){ return name;}

public double getBalance(){ return balance;}

Page 42: Intro to Computer Science I

42BGA

Implementing the class (5)

toString method

public String toString(){ return "BankAccount[" + "number=" + number + ", name=" + name + ", balance=" + balance + "]";}

Page 43: Intro to Computer Science I

43BGA

BankAccount class (1)

public class BankAccount{ private int number; private String name; private double balance;

public BankAccount(int accountNumber, String ownerName, double initialBalance) { number = accountNumber; name = ownerName; balance = initialBalance; }

Page 44: Intro to Computer Science I

44BGA

BankAccount class (2)

public void deposit(double amount) { balance = balance + amount; }

public void withdraw(double amount) { balance = balance – amount; }

public int getNumber() { return number; }

Page 45: Intro to Computer Science I

45BGA

BankAccount class (3)

public String getName() { return name; }

public double getBalance() { return balance; }

public String toString() { return "BankAccount[number=" + number + ", name=" + name + ", balance=" + balance + "]"; }}

Page 46: Intro to Computer Science I

46BGA

BankAccount with BeanShell

addClassPath("c:/book-projects/chapter4/bank-account");BankAccount account = new BankAccount(123, "Fred", 125.50);account.withdraw(100);print(account.getBalance());25.5account.deposit(100);print(account.getBalance());125.5print(account);BankAccount[number=123, name=Fred,balance=125.5]

Page 47: Intro to Computer Science I

47BGA

BankAccount with BlueJ

Page 48: Intro to Computer Science I

48BGA

InitialsMaker description

An InitialsMaker object uses the first and last name of a person to produce the initials in uppercase. For example, if the name is Henry James or henry james then the initials are HJ.

Page 49: Intro to Computer Science I

49BGA

InitialsMaker design

public class InitialsMaker{ // instance data fields go here

public InitialsMaker(String firstName, String lastName) {...}

public String getInitials() {...} public String toString() {...}}

Page 50: Intro to Computer Science I

50BGA

Implementing the class (1)

instance data field

Another possibility

private String initials;

private String firstName;private String lastName;private String initials;

Page 51: Intro to Computer Science I

51BGA

Implementing the class (2)

Constructor

public InitialsMaker(String firstName, String lastName){ initials = firstName.substring(0,1); + lastName.substring(0,1); initials = initials.toUpperCase();}

Page 52: Intro to Computer Science I

52BGA

Implementing the class (3)

get method

toString method

public String getInitials(){ return initials;}

public String toString(){ return "InitialsMaker[initials=" + initials + "]";}

Page 53: Intro to Computer Science I

53BGA

InitialsMaker with BeanShell

addClassPath("c:/book-projects/chapter4/strings");InitialsMaker maker = new InitialsMaker("harry", "James");print(maker.getInitials());HJprint(maker);InitialsMaker[initials=HJ]

Test all four possibilities for the names:"Henry James", "Henry james", "henry James'", "henry james"

Page 54: Intro to Computer Science I

54BGA

PasswordGenerator description

A PasswordGenerator object generates random 7 character passwords. The first four characters should be lower case letters and the last three characters should be digits 0 to 9.

Page 55: Intro to Computer Science I

55BGA

Random number generation

In the Math class there is the random() method that returns a real number

In the java.util package there is a Random class that does what we want.

Constructors and methods public Random() public Random(long seed) public int nextInt()

10 r

repeatable by using the same

seed again

sequence generateddepends on currenttime in milliseconds

10 ni

Page 56: Intro to Computer Science I

56BGA

Random digits and characters

nextInt(10) generates random integer 0,1,...,9 which

can be converted to a character nextInt(26)

generates random integer 0,1, ...,25 which can be used as an index into the string

"abcdefghijklmnopqrstuvwxyz"

to generate a random letter

index 0

index 25

Page 57: Intro to Computer Science I

57BGA

PasswordGenerator design

public class PasswordGenerator{ // instance data fields go here

public PasswordGenerator() {...} public PasswordGenerator(long seed) {...} public String next() {...}}

Each call to next producesa random password

Page 58: Intro to Computer Science I

58BGA

Using the class

First construct PasswordGenerator object PasswordGenerator gen = new PasswordGenerator();

Each call to next returns a random password String p1 = gen.next(); String p2 = gen.next(); String p3 = gen.next();

Page 59: Intro to Computer Science I

59BGA

Implementation (1)

data fields

private static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";

private Random random;

Instance data feld

static class data feld(not associated with any object)

Page 60: Intro to Computer Science I

60BGA

Implementation (2)

Constructors

public PasswordGenerator(){ random = new Random();}

public PasswordGenerator(long seed){ random = new Random(seed);}

Page 61: Intro to Computer Science I

61BGA

Implementation (3)

The next method

public String next(){ int index; String password = ""; index = random.nextInt(26); password = password + LETTERS.substring(index, index + 1); // repeat these two statements three more times index = random.nextInt(10); password = password + index; // repeat these two statements two more times return password;}

Page 62: Intro to Computer Science I

62BGA

Import statement (1)

The Random class is not in the standard java.lang package that is automatically imported into every java class

It is in java.util and needs to be imported excplicity using import java.util.Random;

This statement goes OUTSIDE the class declaration at the top

of the file

Page 63: Intro to Computer Science I

63BGA

Import statement (2)

Another variation is import java.util.*;

This can import and class in the java.util package

If the import statement is not used then it is necesary to use the fully qualified name java.util.Random

of the Random class instead of the short name

Page 64: Intro to Computer Science I

64BGA

Testing the class

addClassPath("c:/book-projects/chapter4/strings");PasswordGenerator gen = new PasswordGenerator();print(gen.next());avfi637print(gen.next());iqde665gen = new PasswordGenerator(); // make a new oneprint(gen.next());zuwe456gen = new PasswordGenerator(123);print(gen.next());eomt574gen = new PasswordGenerator(123);print(gen.next());eomt574

Page 65: Intro to Computer Science I

65BGA

Test with BlueJ

Construct an object Use the next method repeatedly from

the object menu Can also insert the simple method

public test(){ System.out.println(next());}

this.next()

Page 66: Intro to Computer Science I

66BGA

The "this" object

When you write a class and call a method from the same class what is the object on which the method is invoked?

Compare gen.next(); this.next(); next();

Method call expression with an explict object called gen

Method call expression from within the

PasswordGenerator class

If object name is omitted for an instance method the compiler assumes that the

method is in the same class

Page 67: Intro to Computer Science I

67BGA

Association & Aggregation (1)

Programs normally consist of interacting objects from several classes.

Types of classes built-in classes such as String or Random classes obtained from someone else classes you write yourself such as CircleCalculator

The terms association and aggregation are used to describe how classes can relate to each other.

Page 68: Intro to Computer Science I

68BGA

Association (1)

Some classes such as CircleCalculator from Chapter 3 are not related with any other classes.

Others depend on other classes Example

PasswordGenerator uses (depends on) the String and Random classes

This dependence of one class on others is called association

Page 69: Intro to Computer Science I

69BGA

Association (2)

The PasswordGenerator class is associated with, or uses, or depends on the String and Random classes.

The relationship is not symmetric For example, we don't say that the String class is associated with the PasswordGenerator class

The String class is designed to be used by other classes

Page 70: Intro to Computer Science I

70BGA

Association (3)

Class A is associated with class B if A uses B. This can occur in several ways.

An object of B is used as a local variable in a constructor or method in A

An object of B is used as a method or constructor argument in A

An object of B is used as a return value of a method in A

An object of B is an instance data field in A

Page 71: Intro to Computer Science I

71BGA

Aggregation

Aggregation (sometimes called composition) refers to the important last case that an object of B is used as an instance data field of A.

This is gives rise to an object hierarchy Example

Random class is used as instance data fields in PasswordGenerator

Page 72: Intro to Computer Science I

72BGA

TriangleCalculatorTester

public class TriangleCalculatorTester{ public TriangleCalculatorTester() { } public void doTest(double a, double b, double g) { TriangleCalculator tri = new TriangleCalculator(a,b,g); System.out.println("Sides: " + tri.getA() + ", " + tri.getB() + ", " + tri.getC()); System.out.println("Angles: " + tri.getAlpha() + ", " + tri.getBeta() + ", " + tri.getGamma()); System.out.println("Angle sum is " + tri.checkAngleSum()); }}

Association

Can omit constructor

In BlueJ a dotted arrrow indicates association

Page 73: Intro to Computer Science I

73BGA

Association in BlueJ

doTest produces this

output

the dotted arrowindicates

association

TriangleCalculatorTester is associatedwith (uses) TriangleCalculator

Page 74: Intro to Computer Science I

74BGA

Point class design

public class Point{ private double x, y; public Point() {...} public Point(double x, double y){...} public double getX() {...} public double getY() {...} public String toString() {...}}

Page 75: Intro to Computer Science I

75BGA

Point class implementation (2)

public class Point{ private double x, y;

public Point() { x = y = 0.0; } public Point(double x, double y) { this.x = x; this.y = y; }

Page 76: Intro to Computer Science I

76BGA

Point class implementation (2)

public double getX() { return x; } public double getY() { return y; }

public String toString() { return "Point[" + x + ", " + y +"]"; }} // end of class

Page 77: Intro to Computer Science I

77BGA

Testing the Point class

addClassPath("c:/book-projects/chapter4/geometry");import Point; // necessary or we get java.awt.PointPoint origin = new Point(0,0);Point p = new Point(1,2);print(origin);Point[0.0, 0.0]print(p);Point[1.0, 2.0]print(p.getX());1.0print(p.getY());2.0

Page 78: Intro to Computer Science I

78BGA

Designing a circle class

We want to develop a simple Circle class to describe geometric circles in terms of their center (x,y) and radius r

Method 1 Use three double type instance data fields

for the center coordinates and the radius Method 2 (using aggregation)

Use two instance data fields. One is a Point object for the center and the other is the radius

Page 79: Intro to Computer Science I

79BGA

Circle class design (method 1)

public class Circle{ private double x, y, radius; public Circle() {...} public Circle(double x, double y, double r) {...} public double getX() {...} public double getY() {...} public double getRadius() {...} public String toString() {...}}

Page 80: Intro to Computer Science I

80BGA

Circle class design (method 2)

public class Circle{ private Point center; private double radius;

public Circle() {...} public Circle(double x, double y, double r) {...} public Circle(Point c, double r) {...} public Point getCenter() {...} public double getRadius() {...} public String toString() {...}}

aggregation

Page 81: Intro to Computer Science I

81BGA

Implementation (1)

Constructors

public Circle(Point p, double r){ center = p; radius = r;}public Circle(double x, double y, double r){ center = new Point(x,y); radius = r;}public Circle(){ center = new Point(); radius = 1;}

Page 82: Intro to Computer Science I

82BGA

Implementation (2)

Methods

public double getRadius(){ return radius;}

public Point getCenter(){ return center;}

public String toString(){ return "Circle[" + center + ", " + radius + "]";}

Page 83: Intro to Computer Science I

83BGA

Testing the class (BeanShell)

addClassPath("c:/book-projects/chapter4/geometry");import Point;Point center = new Point(3,4);Circle c1 = new Circle();Circle c2 = new Circle(center, 5);Circle c3 = new Circle(3,4,5);print(c1);Circle[Point[0.0, 0.0], 1.0]print(c2);Circle[Point[3.0, 4.0], 5.0]print(c3);Circle[Point[3.0, 4.0], 5.0]double x = c2.getCenter().getX();print(x);3.0

multiple methodcall expressions

Page 84: Intro to Computer Science I

84BGA

Testing the class (BlueJ)

Point object for (3,4)

use it here as

constructor argument

Page 85: Intro to Computer Science I

85BGA

CircleTester (1)

public class CircleTester{ public CircleTester() { }

public void doTest() { Point center = new Point(3,4); Circle c1 = new Circle(); Circle c2 = new Circle(center, 5); Circle c3 = new Circle(3,4,5);

Construct 3 circle objects

can omit constructor

Page 86: Intro to Computer Science I

86BGA

CircleTester (2)

System.out.println("c1 = " + c1); System.out.println("c2 = " + c2); System.out.println("c3 = " + c3);

double radius = c2.getRadius(); double x = c2.getCenter().getX(); double y = c2.getCenter().getY(); System.out.println("Radius = " + radius); System.out.println("Center x = " + x); System.out.println("Center y = " + y);

} // end of doTest method

} // end of CircleTester class

display using

toString

aggregation

Page 87: Intro to Computer Science I

87

Other Library classes

Dates and timesCalendars

Currency formattingnumeric formatting

Page 88: Intro to Computer Science I

88BGA

Date class

Represents dates as the number of milliseconds since January 1, 1970, 00:00:00 GMT as a long value

Example 1055681816162 =

Sun Jun 15 08:56:57 EDT 2003

toString provides this

Page 89: Intro to Computer Science I

89BGA

Date class specification

Some of the constructors and methods arepublic Date()

public Date(long date)

public long getTime()public void setTime(long date)public String toString()

date right now

Date class is in package java.util

Page 90: Intro to Computer Science I

90BGA

Date example (BeanShell)

import java.util.Date;Date now = new Date();print(now);Sun Jun 15 08:56:56 EDT 2003long t = now.getTime();print(t);1055681816162Date first = new Date(0L);print(first);Wed Dec 31 19:00:00 EST 1969first.setTime(0L + 1000L * 60L * 60L * 24L);print(first);Thu Jan 01 19:00:00 EST 1970

We are 5 hours ahead of

midnight GMT

milliseconds in a day

Page 91: Intro to Computer Science I

91BGA

SimpleDateFormat class

We need to be able to display dates in various formats. SimpleDateFormat can do this

Constructors and methods

public SimpleDateFormat()public SimpleDateFormat(String pattern)public String format(Date d);

Convert a Date object to the format specified by the

constructor

This class is inpackage

java.text

Page 92: Intro to Computer Science I

92BGA

Example (BeanShell)

import java.util.Date;import java.text.SimpleDateFormat;Date now = new Date();SimpleDateFormat f1 = new SimpleDateFormat();String n1 = f1.format(now);print(n1);6/15/03 8:56 AMSimpleDateFormat f2 = new SimpleDateFormat("dd/MM/yyyy");print(f2.format(now));15/06/2003SimpleDateFormat f3 = new SimpleDateFormat("HH:mm:ss z");print(f3.format(now));08:56:56 EDT

Page 93: Intro to Computer Science I

93BGA

Calendar class

A higher level class than Date that knows about year, month, day of month, day of year, etc.

Java can use any of the world's calendars depending on the locale.

For us this is the Gregorian calendar

Page 94: Intro to Computer Science I

94BGA

Constructing a Calendar

public static Calendar getInstance()

A constructor is not used to create a Calendar object.Instead a static class methodis used. Method prototype is

Recall that a static method in a class is not associated with any objectsof the class. The Math class methods were like this.

Compare Math.sqrt with Calendar.getInstance

Calendar now = Calendar.getInstance();

This is a static methodcall expression

For a static (class) method the class name is used

instead of an object name

Page 95: Intro to Computer Science I

95BGA

Instance versus static method

Instance method call expression

Static method call expression

objectName.methodName(actualArgumentList)

ClassName.methodName(actualArgumentList)

Page 96: Intro to Computer Science I

96BGA

Some Calendar methods

public Date getTime()

public int get(int field)

public void set(int field, int value)

public void set(int year, int month, int day)

Calendar fields are integer constants such as Calendar.YEAR,

Calendar.MONTH, Calendar.DAY_OF_MONTH

Page 97: Intro to Computer Science I

97BGA

Using Calendar class (1)

import java.util.Date;import java.util.Calendar;Calendar now = Calendar.getInstance();Date time = now.getTime();print(time);Sun Jun 15 10:04:12 EDT 2003print(now.get(Calendar.YEAR));2003print(now.get(Calendar.MONTH)); // Jan is month 05print(now.get(Calendar.DAY_OF_MONTH));15print(now.get(Calendar.DAY_OF_WEEK)); // Sunday is 11

factorymethod

Page 98: Intro to Computer Science I

98BGA

Using Calendar class (2)

print(now.get(Calendar.DAY_OF_YEAR));166

Calendar christmas = Calendar.getInstance();

int year = christmas.get(Calendar.YEAR);

christmas.set(year, Calendar.DECEMBER, 25);print(christmas.getTime());Thu Dec 25 11:13:01 EST 2003

Page 99: Intro to Computer Science I

99BGA

Leap years

import java.util.Calendar;

Calendar feb2003 = Calendar.getInstance();feb2003.set(2003, Calendar.FEBRUARY, 1));

Calendar feb2004 = Calendar.getInstance();feb2004.set(2004, Calendar.FEBRUARY, 1));

print(feb2003.getActualMaximum( Calendar.DAY_OF_MONTH));28print(feb2004.getActualMaximum( Calendar.DAY_OF_MONTH));29

Page 100: Intro to Computer Science I

100BGA

Person class (1)

import java.util.Calendar;

public class Person{ private String name; private int birthYear;

public Person(String name, int birthYear) { this.name = name; this.birthYear = birthYear; }

Page 101: Intro to Computer Science I

101BGA

Person class (2)

public String getName() { return name; }

public int getBirthYear() { return birthYear; }

public int age() { Calendar now = Calendar.getInstance(); return now.get(Calendar.YEAR) - birthYear; }} // end of class

Using a Calendarobject to determine

the person's age

Page 102: Intro to Computer Science I

102BGA

CalendarMonth class (1)

Suppose we want to display a calendar for a given year and month.

We don't need the full complexity of the Calendar class

We can write a simpler version called CalendarMonth called an adapter class

An adpater class is a class which makes another class easier to use in specific problems

Page 103: Intro to Computer Science I

103BGA

CalendarMonth class (2)

We need the following functionality only the year and month parts of a Date are

required We need the day of the week for the first day of the

month We need to know the number of days in the month

properly accounting for leap years in February We need the names of the months so that we can

print headings. This class is called an adapter class since it

provides a simpler more specialized version of a more complicated class.

Page 104: Intro to Computer Science I

104BGA

Class design (specification)

public class CalendarMonth{ public CalendarMonth() {...} public CalendarMonth(int year, int month) {...} public int getYear() {...} public int getMonth() {...} public int dayOfWeek() {...} public int daysInMonth() {...} public String monthName() {...} public String toString() {...}}

for first dayof month(1 to 7)

calendarfor this month

Page 105: Intro to Computer Science I

105BGA

Class implementation (1)

import java.util.Calendar;import java.util.SimpleDateFormatpublic class CalendarMonth{ private Calendar calendar;

public static final int JANUARY = Calendar.JANUARY; ... public static final int SATURDAY = Calendar.SATURDAY.

adapt this class

Constants for month and day names

Page 106: Intro to Computer Science I

106BGA

Class implementation (2)

public CalendarMonth() { calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); }

public CalendarMonth(int year, int month) { calendar = Calendar.getInstance(); calendar.set(year, month, 1); }

set calendar tofirst day of month

Page 107: Intro to Computer Science I

107BGA

Class implementation (3)

public int getYear() { return calendar.get(Calendar.YEAR); }

public int getMonth() { return calendar.get(Calendar.MONTH); }

Page 108: Intro to Computer Science I

108BGA

Class implementation (4)

public int dayOfWeek() { return calendar.get( Calendar.DAY_OF_WEEK); }

public int daysInMonth() { return calendar.getActualMaximim( Calendar.DAY_OF_MONTH); }

1 = Sunday

calendar is already set to first day of

month

Page 109: Intro to Computer Science I

109BGA

Class implementation (5)

public String monthName() { SimpleDateFormat f = new SimpleDateFormat("MMMM"); return f.format(calendar.getTime()); }

public String toString() { SimpleDateFormat f = new SimpleDateFormat("MMMM yyyy"); return f.format(calendar.getTime()); }} // end of class

Page 110: Intro to Computer Science I

110BGA

Using CalendarMonth class (1)

addClassPath("c:/book-projects/chapter4/calendar");

CalendarMonth thisMonth = new CalendarMonth();print(thisMonth.dayOfWeek());2print(thisMonth.daysInMonth());30print(thisMonth.monthName());Septemberprint(thisMonth);September 2003

Monday

Page 111: Intro to Computer Science I

111BGA

Using CalendarMonth class (2)

// continued from previous slide

CalendarMonth feb2004 = new CalendarMonth(2004, CalendarMonth.FEBRUARY);print(feb2004.dayOfWeek());1print(feb2004.daysInMonth());29print(feb2004.monthName());Februaryprint(feb2004);February 2004

our constants

leap year

Sunday

Page 112: Intro to Computer Science I

112BGA

CalendarMonthTester (1)

public class CalendarMonthTester{ public CalendarMonthTester() {} public void doTest() { CalendarMonth thisMonth = new CalendarMonth(); System.out.println("First day of month is " + thisMonth.dayOfWeek()); System.out.println("Number of days in month is " + thisMonth.daysInMonth()); System.out.println("Month name is " + thisMonth.monthName()); System.out.println("Calendar name is " + thisMonth);

Page 113: Intro to Computer Science I

113BGA

CalendarMonthTester (2)

System.out.println(); CalendarMonth feb2004 = new CalendarMonth(2004, CalendarMonth.FEBRUARY);

System.out.println("First day of month is " + thisMonth.dayOfWeek()); System.out.println("Number of days in month is " + thisMonth.daysInMonth()); System.out.println("Month name is " + thisMonth.monthName()); System.out.println("Calendar name is " + thisMonth); } // end of doTest} // end of class

Page 114: Intro to Computer Science I

114BGA

CalendarMonth in Bluej

Page 115: Intro to Computer Science I

115BGA

Currency formatting

Depends on locale English: $100,000.56 French: 100000,56

$ NumberFormat is in java.text package Construct a NumberFormat object

Format it as a string

NumberFormat currency = NumberFormat.getCurrencyInstance();

double salary = 4000.56String value = currency.format(salary);

Page 116: Intro to Computer Science I

116BGA

BeanShell example

import java.text.NumberFormat;double salary = 100000.555;NumberFormat currency = NumberFormat.getCurrencyInstance();print(currency.format(salary));$100,000.56NumberFormat currencyCF = NumberFormat.getCurrencyInstance( Locale.CANADA_FRENCH);print(currencyCF.format(salary));100000,56 $

Page 117: Intro to Computer Science I

117BGA

Formatting fixed numbers

Formatting numbers with a fixed number of digits after decimal point

import java.text.DecimalFormat;DecimalFormat fix = new DecimalFormat(" 0.00000;-0.00000);

print(fix.format(Math.PI)); 3.14159print(fix.format(-Math.PI));-3.14159

format forpositive numbers

format fornegative numbers

Page 118: Intro to Computer Science I

118BGA

Formatting scientific numbers

Formatting numbers with a an exponent and five digits after decimal pointimport java.text.DecimalFormat;

DecimalFormat fix = new DecimalFormat(" 0.00000E000;-0.00000E000);double d = 1.2345678E-23;print(sci.format(d)); 1.23457E-023print(fix.format(d));-1.23457E-023

format forpositive numbers

format fornegative numbers

Page 119: Intro to Computer Science I

119

Review of OOP concepts

constructing objectsobject referencesusing references

data encapsulation and integrityinstance variables and methods

static variables,constants,methods

Page 120: Intro to Computer Science I

120BGA

Constructing objects

Objects are constructed in two ways Using a constructor

Circle c1 = new Circle(3,4,5); or using a static factory method which

returns an object of the class using a static method call expression

Calendar now = Calendar.getInstance();

Page 121: Intro to Computer Science I

121BGA

Constructor Examples

Circle c1 = new Circle(new Point(3,4), 5);Point p = new Point(3,4);Point q = new Point();Circle c1 = new Circle(3, 4, 5);BankAccount a = new BankAccount(123, "Fred", 4000);SimpleDateFormat f = new SimpleDateFormat("MMMM yyyy");

public Circle(Point p, double radius)public Point(double x, double y)public Circle(double x, double y, double radius)public BankAccount(int number, String name, double balance)public SimpleDateFormat(String pattern)

Constructor call expressions (underlined)

Constructor prototypes

Page 122: Intro to Computer Science I

122BGA

Static Factory Examples

Calendar now = Calendar.getInstance();NumberFormat currency = NumberFormat.getCurrencyInstance();

public static Calendar getInstance()public static NumberFormat getCurrencyInstance()

Static method call expressions (underlined)

Static method prototypes

Page 123: Intro to Computer Science I

123BGA

public Circle(double x, double y double r){ center = new Point(x,y); radius = r;}

public Circle(){ center = new Point(); radius = 1;}

Using this as a constructor call

public Circle(Point p, double r){ center = p; radius = r;}

this(new Point(),1);

this(new Point(x,y),r);

"this" will callthis constructor

WARNING

Page 124: Intro to Computer Science I

124BGA

The Default constructor

If you don't put any constructors in a class the default no-arg constructor

is automatically provided by the compiler.

For example in CircleTester we could have omitted the no-arg constructor that was included in the class.

public ClassName(){}

Page 125: Intro to Computer Science I

125BGA

Miranda convention

You have a right to a constructor. If you do not have one, a default one will be provided to you by the compiler.

Page 126: Intro to Computer Science I

126BGA

What does it do?

The default constructor simply supplies default initialization for any uninitialized instance data fields: A value of zero is assigned to all

uniinitialized numeric data fields. A reference value of null is assigned to all

uninitialized data fields of object type (explained later)

Try it: see page 142 of text book

Page 127: Intro to Computer Science I

127BGA

Object references

Constructing an object is a three step process Memory space is allocated for the object

and its instance data fields. A reference (address) to the object is

returned so that it can be located This reference is assigned as the value of

an object reference variable This variable is the object reference

variable

Page 128: Intro to Computer Science I

128BGA

Pictorial representation

ObjectData

ClassNameobjectName

nullobjectName

ClassName objectName =

new ClassName(actualArguments)

ClassName objectName = null;

ClassName objectName;

Page 129: Intro to Computer Science I

129BGA

Circle Example

Circle c;

Circle c = null;

Circle c = new Circle(3,4,5);

Uninitializedreference

null reference

InitializedReference

Page 130: Intro to Computer Science I

130BGA

Primitive and reference types

Primitive types numeric types such as int, long, float,

double

Reference types object types such as String, Circle,

BankAccount

Hello World

Stringgreeting

17.902area

Page 131: Intro to Computer Science I

131BGA

Why do we need both types?

Types such as int and double are primitive types for efficiency reasons. There is a certain amount of overhead in following a reference to find an object.

There are wrapper classes that let us convert the primitive types to object types

Example: Integer class encapsulates an int value

Page 132: Intro to Computer Science I

132BGA

Assignment for reference types

Primitive types: the assignment statement a = b; means to assign the value of b as the value of a.

Reference types: the assignment statement a = b; means to assign the reference b as the value of the reference a and this means that a and b now both reference the same object

assignment does not copy objects.

Page 133: Intro to Computer Science I

133BGA

a=b for primitive types

17a

19b

19a

19b

Before a = b After a = b

Page 134: Intro to Computer Science I

134BGA

a=b for reference types

Before a = b After a = b

a objectA

b objectB

a objectA

b objectB

Page 135: Intro to Computer Science I

135BGA

BankAccount example

BankAccount fred = new BankAccount(123, "Fred", 150.0);BankAccount mary = new BankAccount(345, "Mary", 250.0);mary = fred; // both reference fredmary.withdraw(100.0);print(mary);BankAccount[number=123, name=Fred, 50.0]print(fred);BankAccount[number=123, name=Fred, 50.0]

Page 136: Intro to Computer Science I

136BGA

Where are references used?

Local variables in the constructor or method Example: TriangleCalculator tri = new TriangleCalculator(a,b,g);

Constructor or method arguments Example: public Circle(Point p, double r)

method return values Example: return center;

instance data fields (aggregation) Example: private Calendar calendar;

Page 137: Intro to Computer Science I

137BGA

Data encapsulation (1)

In OOP the data is spread out over the instance data fields of one or more objects

Each object is only responsible for its own data

This data is normally private so that it cannot be directly changed outside the class

This is called data encapsulation.

Page 138: Intro to Computer Science I

138BGA

Data encapsulation (2)

Classes can be mutable or immutable For mutable classes the constructors

and methods that change the values of one or more instance data fields can be written to check that objects are not in an inconsistent state.

Example: See page 146 for discussion of public data fields and set methods.

Page 139: Intro to Computer Science I

139BGA

Side effects

Changing the state of an object indirectly from outside the class

Sometimes this is desirable Sometimes side-effects are undesirable Side-effects are normally created by

returning references from methods that can be used outside the class to change the state of an object.

Page 140: Intro to Computer Science I

140BGA

The MPoint class

Our Point class is immutable: it is not possible to change the state of a Point object after it has been constructed

Consider a mutable version called MPoint like Point but with following set methodspublic void setX(double x){ this.x = x;}public void setY(double y){ this.y = y;}

Page 141: Intro to Computer Science I

141BGA

The MCircle class

Identical to Circle except that it uses aggregation with the mutable MPoint class instead of the immutable Point class

The following constructor has side-effectspublic MCircle(MPoint p, double r){ center = p; radius = r;}

center can be changed through p

Page 142: Intro to Computer Science I

142BGA

Example of side-effect (1)

addClassPath("c:/book-projects/chapter4/side-effects");MPoint p = new MPoint(3,4);MCircle c = new MCircle(p, 5);print(c);MCircle[MPoint[3.0, 4.0], 5.0]p.setX(999);print(c);MCircle[MPoint[999.0, 4.0], 5.0]

The change in the x coordinate of point p outside the MCircle class hasthe side-effect of changing the x coordinate of the center of the circle.

This is normally an undesirable side-effect since it violates the dataencapsulation.

Also try itin BlueJ

Page 143: Intro to Computer Science I

143BGA

Example of side-effect (2)

addClassPath("c:/book-projects/chapter4/side-effects");MCircle c = new MCircle(3, 4, 5);print(c);MCircle[MPoint[3.0, 4.0], 5.0]MPoint p = c.getCenter();p.setX(999);print(c);MCircle[MPoint[999.0, 4.0], 5.0]

Also try itin BlueJ

reference tocenter isreturned

Page 144: Intro to Computer Science I

144BGA

Example of side-effect (3)

The problems occurs with the assignment statement

and with the statement

This gives two references to the same point object. One reference inside the class (center) and one outside the class (p).

center = p;

return center;

Page 145: Intro to Computer Science I

145BGA

Example of side-effect (4)

999x

MPoint

center

5radius

4y

MCircle

p

c

There are two references toone MPoint object

Page 146: Intro to Computer Science I

146BGA

No side-effect in original classes

addClassPath("c:/book-projects/chapter4/geometry");import Point;Point p = new Point(3,4);Circle c = new Circle(p, 5);print(c);Circle[Point[3.0, 4.0], 5.0]MPoint p = c.getCenter();p = new Point(999,4);print(c);Circle[Point[3.0, 4.0], 5.0]

Page 147: Intro to Computer Science I

147BGA

Fixing the side-effect (1)

Include a copy constructor in MPoint class

General form of copy constructor

public MPoint(MPoint p){ x = p.x; y = p.y;}

public ClassName ( ClassName objectName )

Page 148: Intro to Computer Science I

148BGA

Fixing the side-effect (1)

Revise the constructor that takes an MPoint object as an argument

Revise getCenter method

public MCircle(MPoint p, double r){ center = new MPoint(p); radius = r;}

public MPoint getCenter(){ return new MPoint(center);}

Now centerreferences its ownprivate copy of the

MPoint object

Now we return acopy of the private

MPoint object

Page 149: Intro to Computer Science I

149BGA

Side-effects are gone

addClassPath( "c:/book-projects/chapter4/no-side-effects");MPoint p = new MPoint(3,4);MCircle c = new MCircle(p, 5);print(c);MCircle[MPoint[3.0, 4.0], 5.0]p.setX(999);print(c);MCircle[MPoint[3.0, 4.0], 5.0]

This has noeffect on MCircle

Page 150: Intro to Computer Science I

150BGA

Pictorial Representation

999x

MPoint

center

5radius

4y

MCircle

p

c

3x

MPoint

4y

Now p and c arereferences to differentobjects

Page 151: Intro to Computer Science I

151BGA

BankAccount transfer (1)

public class TransferAgent{ public TransferAgent(BankAccount from, BankAccount to) {...} public void transfer(double amount) {...}}

The constructor takes references to the two BankAccount objectsthat participate in the transfer.

The transfer method does the transfer of a given amount fromone account to the other

Page 152: Intro to Computer Science I

152BGA

BankAccount transfer (2)

public class TransferAgent{ private BankAccount from; private BankAccount to;

public TransferAgent(BankAccount from, BankAccount to) { this.from = from; this.to = to; }

public void transfer(double amount) { from.withdraw(amount); to.deposit(amount); }}

Aggregation

bank-account project

Page 153: Intro to Computer Science I

153BGA

Side-effects (1)

The BankAccount class is mutable and there will be side-effects in the TransferAgent class

The side-effects are desired here since the purpose of the transfer method is to change the balances in the two accounts referenced by from and to suplied by the user.

Page 154: Intro to Computer Science I

154BGA

Side-effects (2)

addClassPath("c:/book-projects/chapter4/bank-account");

BankAccount fred = new BankAccount(123,"Fred",1000);BankAccount mary = new BankAccount(345,"Mary",1000);

TransferAgent agent = new TransferAgent(fred, mary);agent.transfer(500);

print(fred);BankAccount[number=123, name=Fred, balance=500]print(mary);BankAccount[number=345, name=Mary, balance=1500]

try it in BlueJ

Page 155: Intro to Computer Science I

155BGA

Instance variables

Instance variables are also called instance data fields

They are declared in the class but outside any method or constructor

Only instance methods have access to these variables

Each object has its own set of instance variables

Page 156: Intro to Computer Science I

156BGA

Instance methods

Instance methods are associated with objects of the class

Instance methods can access the instance data fields

Page 157: Intro to Computer Science I

157BGA

Using an instance method

To use or call an instance method means to invoke it on some object using an instance method call expression

We also say that instance methods are used to send messages to objects.

Page 158: Intro to Computer Science I

158BGA

Examples

int length = name.length();char first = test.toUpperCase.charAt(0);password = password + LETTERS.substring(index,index+1);String upper = test.toUpperCase();account.deposit(100));String firstInitial = firstName.substring(0,1).toUpperCase();double x = c2.getCenter().getX();doCalculations(); // this is the implied objectlong t = now.getTime();String n3 = f3.format(now);

Method call expressions are underlined in red

objectName.methodName(actualArguments)this.methodName(actualArguments)

message composition

Page 159: Intro to Computer Science I

159BGA

prototypes and call expressions

String letter = LETTERS.substring(index, index + 1);

public String substring(int first, int lastPlusOne)

Page 160: Intro to Computer Science I

160BGA

Method composition

Also called message composition

objectName.methodName(args1) . methodName(args2) ... methodName(argsN)

this.methodName(args1) . methodName(args2) ... methodName(argsN)

Page 161: Intro to Computer Science I

161BGA

Static variables (1)

Also called class variables Declared using the static modifier

inside a class but outside any method or constructor declaration.

We have not used them yet Example

private static int count = 0;

Page 162: Intro to Computer Science I

162BGA

Static variables (2)

They are not associated with any objects.

They belong to the class. Each static variable is shared by all the

objects of the class (shared variable) This is very different from instance

variables1 2 3

0count

4

Page 163: Intro to Computer Science I

163BGA

Static constants

Constants are declared to be static since there is no need to have separate copies of a constant, one for each object.

Examplespublic static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";

public static final int JANAURY = Calendar.JANUARY;

Page 164: Intro to Computer Science I

164BGA

Static methods (1)

They are methods that are not associated with any objects of a class.

To use them in another class prefix the name of the method with the class namebeta = Math.toDegrees(beta);

System.out.println("Area: " + area);Calendar now = Calendar.getInstance();NumberFormat currency = NumberFormat.getCurrencyInstance();

Static method call expressions are underlined in red

Page 165: Intro to Computer Science I

165BGA

Static Methods (2)

General syntax instance method call expressions

General syntax for static method call expressions

(1) objectName.methodName(actualArguments)(2) this.methodName(actualArguments)

(1) className.methodName(actualArguments)(2) methodName(actualArguments)

Page 166: Intro to Computer Science I

166BGA

Counting objects (1)

We can illustrate static variables (shared varibles) and static methods by writing a version of the Point class that keeps track of the number of Point objects that have been counted so far.

Add following static data field to the Point class

public static int count = 0;

Page 167: Intro to Computer Science I

167BGA

Counting objects (2)

Add the following statement to the body of each different constructor (but not if "this" is used)

Add the following static method to the classpublic static int getCount(){ return count;}

count++;

Page 168: Intro to Computer Science I

168BGA

Testing Point (BeanShell)

addClassPath( "c:/book-projects/chapter4/static-variable");import Point;Point p1 = new Point(1,2);Point p2 = new Point(3,4);Point p3 = new Point(4.5);Point p4 = p1;int objectCount = Point.getCount();print(objectName);3

this does notcreate a new object

Also try it with BlueJNote that static methods appear on the Constructor menunot the object menu.

Page 169: Intro to Computer Science I

169BGA

Classifying variables and args

Instance data fields instance variables associated with objects

Static (class) data fields static variables not associated with objects

Local variables declared in the body a constructor or method and

are only accessible there Formal arguments

declared in method or constructor prototype and are local variables

Page 170: Intro to Computer Science I

170BGA

Call by value

Argument passing mechanism is always call by value in Java: if an actual argument is a variable then a

copy of its value is supplied as the value of the formal argument.

If an actual argument is a literal (literal string or number for example) then this value is supplied as the value of the formal argument

If an actual argument is an expression then it is evaluated and its value is supplied as the value of the formal argument.

Page 171: Intro to Computer Science I

171BGA

Call by value (primitive type)

If a constructor or method argument is a primitive type and a variable is used as an actual argument, then the value of the variable can never be changed by the method or constructor since only a copy of the variable's value, not its location, is passed to the method.

Page 172: Intro to Computer Science I

172BGA

Example (BeanShell)

void addOne(int k) { k = k + 1; }int m = 5;addOne(m);print(m);5print(k);// Error: indefined variable

The value of m is not changed by the addOne methodsince only the value 5 is passed to the method so themethod simply adds 1 to the local variable k whichdisappears anyway when the method exits.

static methods can be defined directly

in BeanShell

Page 173: Intro to Computer Science I

173BGA

Example (BlueJ)

Write the following simple class

public class ArgumentTester1{ public void doTest() { int m = 5; addOne(m); System.out.println(m); } private static void addOne(int k) { k = k + 1; }} arguments project in Chapter 4

Page 174: Intro to Computer Science I

174BGA

Call by value (reference type)

For reference type (object type) the situation is quite different

We still use "call by value" but now the value passed is a copy of a reference to the caller's object so there will now be two references to the caller's object

In the case of mutable classes this means that the caller's object can be changed (side-effect).

Page 175: Intro to Computer Science I

175BGA

Example (BeanShell)

addClassPath("c:/book-projects/chapter4/arguments");void addOne(BankAccount b) { b.deposit(1) }BankAccount a = new BankAccount(123,"Fred",1000);addOneDollar(a);print(a);BankAccount[number=123, name=Fred, balance=1001.0]

The value of a is not changed by the addOneDollar methodbut since a is a reference to a BankAccount then the depositstatement does change the balance of the caller's accountas referenced by a

Page 176: Intro to Computer Science I

176BGA

Example (BlueJ)

Write the following simple class

public class ArgumentTester2{ public void doTest() { BankAccount a = new BankAccount(123, "Fred", 1000); addOneDollar(a); System.out.println(a); } private static void addOneDollar(BankAccount b) { b.deposit(1); }}

arguments project in Chapter 4

Page 177: Intro to Computer Science I

177BGA

Pictorial Representation

BankAccount

1001

balance

a

BankAccount

1000

balance

a

BankAccount

1001

balance

a

b

Beforemethodcall

Duringmethodcall

AftermethodcallReference b is local to method

so it has disappeared

Page 178: Intro to Computer Science I

178BGA

The main method (1)

Executing a class outside the BlueJ environment

The JRE (java run time environment) has an interpreter that can be run from the command line using a command prompt

For this to work the class must have a special static method called the main method

Page 179: Intro to Computer Science I

179BGA

Main method (2)

Form of the main method must be

public static void main(String[] args){ ...}

We won't usethis argumentuntil Chapter 8but it must be

there

The java interpreter will beginexecuting your program at thefirst statement in the main method.

This method is normally used onlyto create an object of the class thatstarts your program

Page 180: Intro to Computer Science I

180BGA

Adding a main method

Add a main method to the CircleTester classpublic class CircleTester

{ ... public void doTest() { ... }

public static void main(String[] args) { CircleTester tester = new CircleTester(); tester.doTest(); }}

main will constructa CircleTester object

and run the test

see main-method project

Can also execute main method from inside BlueJ

Page 181: Intro to Computer Science I

181BGA

Another approach

If you don't want to add a main method to the class you want to run you can write a special class that only has a main method

This main method can construct an object of the other class and execute its methods.

Page 182: Intro to Computer Science I

182BGA

BankAccountRunner

public class BankAccountRunner{ public void doTest() { BankAccount account = new BankAccount(123, "Fred", 125.50); System.out.println("Initial balance is " + account.getBalance(); account.withdraw(100); System.out.println("Balance is " + account.getBalance(); ... }

public static void main(String[] args) { BankAccountRunner runner = new BankAccountRunner(); runner.doTest(); }}

uses defaultconstructor

Page 183: Intro to Computer Science I

183BGA

Run from command line

cd to the directory containing the BankAccountRunner class c:\book-projects\chapter4\main-method

Compile the class (if you haven't used BlueJ to do it) javac BankAccountRunner.java

Now run the class using its main method java BankAccountRunner

Page 184: Intro to Computer Science I

184BGA

BankAccountRunner output

java BankAccountRunner

Initial balance is 125.5Balance is 25.5Balance is 125.5BankAccount[number=123, name=Fred, balance=125.5]

interpretercommand

output produced bySystem.out.println

statements