Transcript Week7

CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101/
Week 7: Defining Your Own Classes – Part 2
 Previous lecture:
 Chapter 6: Repetition Statements (cont’d)
 Writing Modular Programs
 Testing and Debugging
 This week:
 Chapter 7: Defining Your Own Classes – Part 2
 Next week:
 Chapter 9: Characters and Strings
 Chapter 10: Arrays and Collections
© CS1101 (AY2009-2010 Semester 1)
Week7 - 2
Welcome Back!
 ARE YOU ENERGISED?
© CS1101 (AY2009-2010 Semester 1)
Week7 - 3
MasterMind


Have you completed your program?
Show it to us!
© CS1101 (AY2009-2010 Semester 1)
Week7 - 4
Chapter 7

Let’ go over Thomas Wu’s slides now…
© CS1101 (AY2009-2010 Semester 1)
Week7 - 5
Method Invocation (1/3)

Given the following
public void setRadius(double r) {
…
}
public static void main(String[] args) {
…
ball.setRadius(s);
}



r is called the formal parameter
s is the actual parameter
Pass-by-value: The value of s is copied into r.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 6
Method Invocation (2/3)


Actual parameters provide information that is
otherwise unavailable to a method
When a method is invoked





Java sets aside memory for that particular invocation, called
the activation record
Activation record stores, among other things, the values of
the formal parameters
Formal parameters initialized with the values of the actual
parameters
After initialization, the actual parameters and formal
parameters are independent of each other
Flow of control is transferred temporarily to that method
© CS1101 (AY2009-2010 Semester 1)
Week7 - 7
Method Invocation (3/3)

Java divides the memory allocated to a
program into two portions: stack and heap.


Activation records are maintained in the stack.
Space for objects comes from the heap.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 8
Default Constructor

A default empty constructor is created
automatically for you if you don’t have any
constructor in your class:
public classname (){
}

However, if you have defined some
constructor(s) for the class, no default
constructor will be created.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 9
Using Constructors

Download the following programs from the module
website (“Resources” – “Lectures”)



Which of the following lines are valid when added into
the main() method in TestMyClass?
a)
b)
c)
d)
+
MyClass.java
TestMyClass.java
MyClass
MyClass
MyClass
MyClass
© CS1101 (AY2009-2010 Semester 1)
a
b
c
d
=
=
=
=
new
new
new
new
MyClass(10, 3);
MyClass(10);
MyClass(10, 1.5);
MyClass();
Week7 - 10
Example of Overloaded Methods

Refer to the abs() method in Math class.
public static int abs(int num)
Returns the absolute value of num.
public static double abs(double num)
Returns the absolute value of num.

Hence, you may use abs() like this:
int num = Math.abs(-40);
double x = Math.abs(-3.7);
© CS1101 (AY2009-2010 Semester 1)
Week7 - 11
So you think you know all about
overloading? (1/2)

Given the following overloaded method
public static void f(int a, int b) {
System.out.println(a + b);
}
public static void f(double a, double b) {
System.out.println(a – b);
}

What are the outputs of the following codes?
f(3, 6);
f(3.0, 6.0);
f(3, 6.0);
© CS1101 (AY2009-2010 Semester 1)
Week7 - 12
So you think you know all about
overloading? (2/2)

How about this
public static void g(int a, double b) {
System.out.println(a + b);
}
public static void g(double a, int b) {
System.out.println(a – b);
}

What is the output of the following code?
g(3, 6);
© CS1101 (AY2009-2010 Semester 1)
Week7 - 13
Instance Methods and Class Methods (1/4)
 There are two types of method.
 Instance method
 Operates on an instance (object) of a class
 Example: The length() method in String class
String str = "Hello";
int len = str.length();
 Class method
 Do not need to call it on an instance (object).
 Examples:
double ans = Math.abs(-4.5);
char ch = Character.toUpperCase('e');
Week7 - 14
Instance Methods and Class Methods (2/4)
 How do we know a method is an instance

method or a class method?
Look at the API page
 If you see the ‘static’ modifier, it is a class method.
 If not, then it is an instance method.
abs() is a class method.
length() is an instance
method.
Week7 - 15
Instance Methods and Class Methods (3/4)
 Some classes provide only class methods
 Example: Math
 Some classes provide only instance methods
 Example: Scanner
 Some classes provide a mix
 Example: String
Week7 - 16
Instance Methods and Class Methods (4/4)
 When writing your own class, how do you decide
whether a method should be a class method or an
instance method?
 Ask these questions:
 “Is it necessary to create an instance in the application
program?”
 “Is it necessary to call this method on individual instance
(object) in order to access/retrieve some information pertaining
only to that instance?”
 If answers are yes  make it an instance method
 If answers are no  make it a class method
 If answers are mixed/not clear  use your judgement!
Week7 - 17
Calling a class method

You call a class method by preceding the call
with the name of the class that contains the
method


Examples: Math.abs(n), String.valueOf(1.23)
If the class method is called within the said
class itself, it is optional to indicate the class

Example: AsterisksV2.java
We may call printStars(2*i-1) or
AsterisksV2.printStars(2*i-1)
© CS1101 (AY2009-2010 Semester 1)
Week7 - 18
Tracing codes

Download the following programs from the module
website (“Resources” – “Lectures”)




Without running the programs, trace the code and
write down the output.
Download the following programs from the module
website (“Resources” – “Lectures”)



Vehicle.java
TestVehicle.java
Foo.java
TestFoo.java
Without running the programs, trace the code and
write down the output.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 19
Modular Programming Revisit (1/2)

Previous lecture:




We compared PrimeTestNonModular.java with
PrimeTest.java.
We put the useful isPrime(int) method in Prime
class for reusability.
We wrote an application CountPrimes.java to use
the isPrime(int) method in Prime.
The isPrime(int) method in Prime is a class
method. Can we write it as an instance
method?
© CS1101 (AY2009-2010 Semester 1)
Week7 - 20
Modular Programming Revisit (2/2)



Try it out! Call the new class PrimeV2 to
avoid confusion.
Call the application program CountPrimesV2,
which is the counterpart of CountPrimes, to
count the number of primes between two
values, using the method in PrimeV2.
Let’s compare PrimeV2 with Prime, and
CountPrimesV2 with CountPrimes.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 21
private vs public

When do we write a private method?


When we don’t want or there is no need for any
other class to use this method.
It also arises when we do modularisation.
public … XX(…) {
...
code-fragment-1
code-fragment-2
...
}
public … XX(…) {
...
YY(…);
ZZ(…);
...
}
private … YY(…) {
code-fragment-1
}
private … ZZ(…) {
code-fragment-2
}
© CS1101 (AY2009-2010 Semester 1)
Week7 - 22
BallV3

We will enhance our Ball class into version 3
to include the following features:






Using ‘this’ in mutators
Using overloaded constructors
Creating a toString() method
Creating an equals() method
Call this BallV3.java
Write an application program TestBallV3.java
to create two ball objects, print their values,
and compare them.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 23
BallV3: toString() method (1/2)

Given the following statements:
System.out.println("1st ball: " + myBall1);
System.out.println("2nd ball: " + myBall2);

where myBall1 and myBall2 are two objects
The output will look like this (actual output may differ
slightly from below):
1st ball: BallV3@10ef90c
2nd ball: BallV3@a32b

Hashcodes
How do you get a custom-made output like this?
1st ball: [blue, 1.2, (8, 3)]
2nd ball: [red, 3.5, (-5, 12)]
© CS1101 (AY2009-2010 Semester 1)
Week7 - 24
BallV3: toString() method (2/2)



To make it work, you need to write the toString()
method.
The toString() method returns a string, which is a
string representation of the data in an object.
Note that after toString() method is defined in BallV3,
you may print myBall1 object in any of these 2 ways:
System.out.println(myBall1);
or
System.out.println(myBall1.toString());

Let’s add the toString() method now.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 25
BallV3: equals() method (1/2)

We create two objects myBall1 and myBall2 with the
same values.


What is the truth value of (myBall1 == myBall2)?
Why is it so?
myBall1
myBall2
:BallV3
:BallV3
colour
red
colour
red
radius
2.3
radius
2.3
xCoord
10
xCoord
10
yCoord
6
yCoord
6
© CS1101 (AY2009-2010 Semester 1)
Week7 - 26
BallV3: equals() method (2/2)

We need to write an equals() method



Where should it be? In BallV3 or TestBallV3?
Why?
Let’s write the equals() method now
© CS1101 (AY2009-2010 Semester 1)
Week7 - 27
Inherited methods and Overriding
(1/3)




The BallV3 class, like every other Java class, is an
extension (subclass) of class Object
Class Object specifies some basic behaviors common
to all objects
Hence, these behaviors are inherited by all Java
classes.
Some inherited Object methods are



toString() method
equals() method
However, the inherited methods usually don’t work (!)
because they are not customised
© CS1101 (AY2009-2010 Semester 1)
Week7 - 28
Inherited methods and Overriding
(2/3)




+
Hence, we often (almost always) need to customise
these inherited methods
This is called overriding
We have written an overriding method toString() for
BallV3
However, the equals() method we just wrote for BallV3
is not an overriding method. Why?
© CS1101 (AY2009-2010 Semester 1)
Week7 - 29
Inherited methods and Overriding
(3/3)




Hence, to provide a truly overriding method for
equals(), this is what you need to write…
(At the end of the day, it doesn’t matter which version
you write.)
You will find overriding methods toString() and equals()
in many classes (see Point class for an example)
We should write overriding methods toString() and
equals() for our own classes
© CS1101 (AY2009-2010 Semester 1)
Week7 - 30
TestBallV3: Modularisation (1/2)

Observe that there are duplicate codes in the input
section of TestBallV3.java. It makes sense to write a
method to read a ball’s data, create the object, and
return it.
System.out.print("Enter colour: ");
inputColour = scanner.next();
System.print("Enter radius: ");
Identical code
inputRadius = scanner.nextDouble();
System.out.print("Enter centre’s x- and y-coordinates: ");
inputXCoord = scanner.nextInt();
inputYCoord = scanner.nextInt();
BallV3 myBall1 = new BallV3(inputColour, inputRadius, inputXCoord, inputYCoord);
System.out.print("Enter colour: ");
inputColour = scanner.next();
System.print("Enter radius: ");
inputRadius = scanner.nextDouble();
System.out.print("Enter centre’s x- and y-coordinates: ");
inputXCoord = scanner.nextInt();
inputYCoord = scanner.nextInt();
BallV3 myBall2 = new BallV3(inputColour, inputRadius, inputXCoord, inputYCoord);
© CS1101 (AY2009-2010 Semester 1)
Week7 - 31
TestBallV3: Modularisation (2/2)


Can you ‘modularise’ TestBallV3.java so that you call a
method readBall() each time you want to create a
BallV3 object?
The follow code can then replace the previous:
BallV3 myBall1 = readBall(scanner);
BallV3 myBall2 = readBall(scanner);



We pass in the Scanner object scanner so that we create only one
instance of Scanner in our program.
Note that CourseMarker doesn’t work if we create multiple instances of
Scanner.
However, we are doing this not to avoid this CourseMarker problem, but
it is not necessary to create multiple instances of Scanner, at least in this
program.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 32
Point class (1/2)



We will introduce the Point class
Textbook section 5.6 Drawing Graphics
Package: java.awt.*
Field Summary
int x
int y
The x coordinate.
The y coordinate.
Constructor Summary
Point()
Constructs and initializes a point at the origin (0, 0) of the coordinate space.
Point(int x, int y)
Constructs and initializes a point at the specified (x, y) location in the coordinate space.
Point(Point p)
Constructs and initializes a point with the same location as the specified Point object.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 33
Point class (2/2)
Method Summary
boolea
n
Point
equals(Object obj)
Determines whether or not two points are equal.
getLocation()
Returns the location of this point.
doubl
e
getX()
doubl
e
getY()
void
Returns the X coordinate of the point in double precision.
Returns the Y coordinate of the point in double precision.
move(int x, int y)
Moves this point to the specified location in the (x, y) coordinate plane.
void
setLocation(double x, double y)
Sets the location of this point to the specified double coordinates.
void
setLocation(int x, int y)
Changes the point to have the specified location.
void
setLocation(Point p)
Sets the location of the point to the specified location.
String
toString()
Returns a string representation of this point and its location in the (x, y) coordinate space.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 34
Using Point class (1/6)

TestPoint.java
import java.awt.*;
class TestPoint {
public static void f(Point v) {
v = new Point(0, 0);
}
public static void g(Point v) {
v.setLocation(0, 0);
}
public static void main(String[] args) {
Point p = new Point(10, 10);
System.out.println(p);
f(p);
System.out.println(p);
g(p);
System.out.println(p);
}
}
+
© CS1101 (AY2009-2010 Semester 1)
Week7 - 35
Using Point class (2/6)
public static void main(String[] args) {
Point p = new Point(10, 10);
public static
System.out.println(p);
void f(Point v) {
v = new Point(0, 0);
}
f(p);
main()
:Point
p
x: 10
y: 10
f()
v
Output:
java.awt.Point[x=10,y=10]
© CS1101 (AY2009-2010 Semester 1)
Method main()’s variable p and method
f()’s formal parameter v have the same
value, which is a reference to an object
representing location (10,10).
Week7 - 36
Using Point class (3/6)
public static void main(String[] args) {
Point p = new Point(10, 10);
public static
System.out.println(p);
void f(Point v) {
v = new Point(0, 0);
}
f(p);
main()
:Point
p
y: 10
x: 10
f()
v
Output:
java.awt.Point[x=10,y=10]
© CS1101 (AY2009-2010 Semester 1)
:Point
x: 0
y: 0
Week7 - 37
Using Point class (4/6)
public static void main(String[] args) {
Point p = new Point(10, 10);
System.out.println(p);
f(p);
System.out.println(p);
main()
:Point
p
y: 10
x: 10
f()
v
Output:
java.awt.Point[x=10,y=10]
:Point
x: 0
y: 0
java.awt.Point[x=10,y=10]
© CS1101 (AY2009-2010 Semester 1)
Week7 - 38
Using Point class (5/6)
public static void main(String[] args) {
Point p = new Point(10, 10);
public static
System.out.println(p);
void g(Point v) {
v.setLocation(0, 0);
}
f(p);
System.out.println(p);
g(p);
main()
:Point
p
x: 10 0
y: 10 0
g()
v
Output:
java.awt.Point[x=10,y=10]
java.awt.Point[x=10,y=10]
© CS1101 (AY2009-2010 Semester 1)
Week7 - 39
Using Point class (6/6)
public static void main(String[] args) {
Point p = new Point(10, 10);
System.out.println(p);
f(p);
System.out.println(p);
g(p);
System.out.println(p);
main()
:Point
p
x: 10 0
y: 10 0
Output:
java.awt.Point[x=10,y=10]
java.awt.Point[x=10,y=10]
java.awt.Point[x=0,y=0]
© CS1101 (AY2009-2010 Semester 1)
Week7 - 40
Other Point related classes

Check them out


Point2D.Double
Point2D.Float
© CS1101 (AY2009-2010 Semester 1)
Week7 - 41
Common mistake

Common mistake with using objects


Note that declaring an object  creating an
object


Accessing an object when it does not exist
Only a new statement creates an object
(exception: String)
The following is wrong:
Point pt;
System.out.println(pt.getX());
pt.setLocation(10, 20);
© CS1101 (AY2009-2010 Semester 1)
Week7 - 42
BallV4: Using Point for centre





Currently, we use xCoord and yCoord to represent
the centre of a ball object.
Now, enhance your Ball class into version 4 by
replacing xCoord and yCoord with Point for the
centre.
Call this BallV4.java
Write an application program TestBallV4.java to
create two ball objects, print their values, and
compare them.
Please bring along your programs to your discussion
session this Friday. Your DL will check your programs
and discuss them.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 43
Summary for Today


Writing modular programs revisit
More about OOP






Instance method vs class method
Using private vs public method
Using ‘this’
Overloading methods
Overriding methods
The Point class
© CS1101 (AY2009-2010 Semester 1)
Week7 - 44
Announcements/Things-to-do (1/2)

Complete the following


To prepare for next lecture


BallV4.java and TestBallV4.java
Read Chapters 9 – 10 and their PowerPoint files
before you come for lecture.
To prepare for this Friday’s discussion
session:

Download “week7_discussion_qns.pdf” from
module website, “CA – Discussion”.

Do the questions before you attend your
discussion session.
© CS1101 (AY2009-2010 Semester 1)
Week7 - 45
Announcements/Things-to-do (2/2)

Take-home Lab #4


This lab will take you more time than the previous
labs. Please start working on it early. You may
clarify your doubts at this Friday’s discussion
session or at the next lecture.
Mid-term test


This Saturday, 3 October 2009
Refer to module website (“CA” – “Termtests”) for
details
© CS1101 (AY2009-2010 Semester 1)
Week7 - 46
End of File
© CS1101 (AY2009-2010 Semester 1)
Week7 - 47