chapter2-Object and Class

Download Report

Transcript chapter2-Object and Class

Chapter 2
Objects and Classes
1
Objectives














To understand objects and classes and use classes to model objects.
To learn how to declare a class and how to create an object of a class.
To understand the roles of constructors and use constructors to create objects.
To use UML graphical notations to describe classes and objects.
To distinguish between object reference variables and primitive data type
variables.
To use classes in the Java library.
To declare private data fields with appropriate get and set methods to make class
easy to maintain.
To develop methods with object arguments.
To understand the difference between instance and static variables and methods.
To determine the scope of variables in the context of a class.
To use the keyword this as the reference to the current object that invokes the
instance method.
To store and process objects in arrays.
To apply class abstraction to develop software.
To declare inner classes.
2
OO Programming Concepts




Objects
Object-oriented programming (OOP) involves
programming using objects.
An object represents or an abstraction of some
entity in the real world that can be distinctly
identified.
 For example, a student, a desk, a circle, a
button, a cow, a car, a loan, and etc.
An object may be physical, like a radio, or
intangible, like a song.
Just as a noun is a person, place, or thing; so is
3
an object
OO Programming Concepts
 An object has a unique identity
 State or characteristics or attributes, and
 Action or behaviors.
 Specifically, an object is an entity that consists
of:
 a set of data fields (also known as properties
or attributes) with their current values.
 A set of methods that use or manipulate the
data ( the behaviors).
4
Objects – Example 1
Class Name: Circle
A class template
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Circle Object 2
Circle Object 3
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is 125
Three objects of
the Circle class
An object has both a state and behavior. The state
defines the object, and the behavior defines what
the object does.
5
Objects – Example 2



A remote control unit is an object.
A remote control object has three attributes:
– the current channel, an integer,
– the volume level, an integer, and
– the current state of the TV, on or off, true or false,
Along with five behaviors or methods:
– raise the volume by one unit,
– lower the volume by one unit,
– increase the channel number by one,
– decrease the channel number by one, and
– switch the TV on or off.
Objects – Example 2 (Cont.)
Three different remote objects, each with unique attribute values (data) but all sharing the
same methods or behaviors.
Objects – Example 2 (Cont.)
The remote control unit exemplifies encapsulation.
 Encapsulation is defined as the language feature of
packaging attributes and behaviors into a single
unit.
 Data and methods comprise a single entity.
 Each remote control object encapsulates data and
methods, attributes and behaviors.
 An individual remote unit, an object, stores its own
attributes – channel number, volume level, power
state – and has the functionality to change those
attributes.
Objects – Example 3
A
rectangle is an object.
 The
attributes of a rectangle might be length and
width, two floating point numbers; the methods
compute and return area and perimeter.
 Each
rectangle has its own set of attributes; all share
the same behaviors
Objects – Example 3 (Cont.)
Three rectangle objects
Objects – Example 4
Three String Objects


A character string is an object that encapsulates
data and methods.
The string data consists of an ordered sequence of
characters and two (of many) methods include a
method that returns the number of characters in the
th
String and one that returns the i character
Classes
 Class is a template or blueprint, from which
objects of the same type are created.
 A Java class uses
 variables to define data fields and
 methods to define behaviors.
 Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
12
Unified Modelling Language
(UML) Class Diagram
Circle
UML Class Diagram
Class name
radius: double
Data fields
Circle()
Constructors and
Methods
Circle(newRadius: double)
getArea(): double
circle1: Circle
radius: 10
circle2: Circle
radius: 25
circle3: Circle
UML notation
for objects
radius: 125
13
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
Data field
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
Method
}
14
Classes – Exercise 1
Rectangle Class

A Rectangle class might specify that every Rectangle object consists of
two variables of type double:
– double length, and
– double width,

Every Rectangle object comes equipped with two methods:
– double area(), and
//returns the area, length x width,
– double perimeter(), //returns the perimeter, 2(length + width).

Individual Rectangle objects may differ in dimension but all Rectangle
objects share the same methods

Question:
•
•
Draw a UML class diagram of rectangle class
Create a rectangle class
Constructors
Circle() {
}
Constructors are a special
kind of methods that are
invoked to construct objects.
Circle(double newRadius) {
radius = newRadius;
}
16
Constructors (Cont.)
 A constructor with no parameters is referred to as a
no-arg constructor.
 Constructors must have the same name as the class
itself.
 Constructors do not have a return type—not even
void.
 Constructors are invoked using the new operator
when an object is created.
 Constructors play the role of initializing objects.
17
Creating Objects Using
Constructors
Syntax:
new ClassName();
Example:
new Circle();
new Circle(5.0);
18
Default Constructor
 A class may be declared without constructors.
 In this case, a no-arg constructor with an empty
body is implicitly declared in the class.
 This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
19
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
20
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference
Create an object
Example:
Circle myCircle = new Circle();
21
Accessing Objects
Data field can be accessed and its methods invoked
using the dot operator (.) – known as object member
access operator.
 Referencing the object’s data:

objectRefVar.data
e.g., myCircle.radius

Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
22
A Simple Circle Class
 Objective:
Demonstrate creating objects,
accessing data, and using methods.
TestCircle1
Run
23
animation
Trace Code
Declare myCircle
Circle myCircle = new Circle(5.0);
myCircle
no value
SCircle yourCircle = new Circle();
yourCircle.radius = 100;
24
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle
no value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
Create a circle
25
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
Assign object reference
to myCircle
: Circle
radius: 5.0
26
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle
no value
Declare yourCircle
27
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
no value
yourCircle
: Circle
Create a new
Circle object
radius: 0.0
28
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
yourCircle reference value
Assign object reference
to yourCircle
: Circle
radius: 1.0
29
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle reference value
: Circle
Change radius in
yourCircle
radius: 100.0
30
1. public class TestCircle1 {
2.
public static void main(String[] args) {
3.
Circle1 myCircle = new Circle1(5.0);
4.
System.out.println(“The area of the circle of radius “ +
5.
myCircle.radius + “ is “ +
6.
myCircle.getArea());
7.
Circle1 yourCircle = new Circle1();
8.
System.out.println(“The area of the circle of radius “ +
9.
yourCircle.radius + “ is “ +
10.
yourCircle.getArea());
11.
yourCircle.radius = 100;
12.
System.out.println(“The area of the circle of radius “ +
13.
yourCircle.radius + “ is “ +
14.
yourCircle.getArea());
15.
}
16. }
31
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
class Circle1 {
double radius;
Circle1( ) {
radius = 1.0;
}
Circle1(double newRadius) {
radius = newRadius;
}
double getArea( ) {
return radius * radius * radius *
Math.PI;
}
}
32
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class. Can you invoke getArea() using
Circle1.getArea()? The answer is no. All the methods used before this
chapter are static methods, which are defined using the static keyword.
However, getArea() is non-static. It must be invoked from an object
using
objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).
More explanations will be given in Section 2.7, “Static Variables,
Constants, and Methods.”
33
Reference Data Fields
The data fields can be of reference types. For example,
the following Student class contains a data field name of
the String type.
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}
34
The null Value
If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.
35
Default Value for a Data Field
The default value of a data field is null for a
reference type, 0 for a numeric type, false for a
boolean type, and '\u0000' for a char type.
However, Java assigns no default value to a local
variable inside a method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
36
Example
Java assigns no default value to a local variable
inside a method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error: variables not
initialized
37
1. public class TestCircle1 {
2.
public static void main(String[] args) {
3.
double localVar;
4.
//Circle1 myCircle = new Circle1(5.0);
5.
//System.out.println(“The area of the circle of radius “ +
6.
myCircle.radius + “ is “ +
7.
myCircle.getArea());
8.
Circle1 yourCircle = new Circle1();
9.
System.out.println(“The default value for radius is “ +
10.
yourCircle.radius);
11.
System.out.println(“Default value for local variable is “ +
12.
localVar);
13.
// yourCircle.radius = 100;
14.
//System.out.println(“The area of the circle of radius “ +
15.
yourCircle.radius + “ is “ +
16.
yourCircle.getArea());
17.
}
18.
}
38
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
class Circle1 {
double radius;
Circle1( ) {
//
radius = 1.0;
}
Circle1(double newRadius) {
radius = newRadius;
}
double getArea( ) {
return radius * radius * radius *
Math.PI;
}
}
39
Differences between Variables of
Primitive Data Types and Object Types
Created using new Circle()
Primitive type
int i = 1
i
1
Object type
Circle c
c
reference
c: Circle
radius = 1
40
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j
Before:
After:
i
1
i
2
j
2
j
2
Object type assignment c1 = c2
Before:
After:
c1
c1
c2
c2
c1: Circle
C2: Circle
c1: Circle
C2: Circle
radius = 5
radius = 9
radius = 5
radius = 9
41
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2,
 c1 points to the same object referenced by
c2.
 The object previously referenced by c1 is
no longer referenced.
 This object is known as garbage.
This clean-up process is called garbage
collection
Garbage is automatically collected by Java
Virtual Machine (JVM).
42
Garbage Collection, cont
TIP: If you know that an object is no
longer needed, you can explicitly assign
null to a reference variable for the
object. The JVM will automatically
collect the space if the object is not
referenced by any variable.
43
Garbage Collection, cont

If an object remains referenced but is no longer used in a program, the garbage collector does not recycle
the memory:
Square mySquare = new Square (5.0);
double areaSquare = mySquare.area();
// a 5.0 x 5.0 square
Triangle myTriangle = new Triangle(6.0, 8.0);
double areaTriangle = myTriangle.area();
// right triangle base = 6.0, height = 8.0
Circle myCircle = new Circle(4.0);
// a circle of radius 4.0
double areaCircle = myCirclearea();
…
// code that uses these objects
…
// more code that does not use the objects created above
...

When Square, Triangle and Circle objects are no longer used by the program, if the objects remain
referenced, that is, if references mySquare, myTriangle, and myCircle continue to hold the addresses of
these obsolete objects, the garbage collector will not reclaim the memory for these three objects.

Such a scenario causes a memory leak.
44
Garbage Collection, cont


A memory leak occurs when an application fails to release or recycle memory that is no longer needed.
The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a few
lines of code :
Square mySquare = new Square (5.0);
double areaSquare = mySquare.area();
// a 5.0 x 5.0 square
Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0
double areaTriangle = myTriangle.area();
Circle myCircle = new Circle(4.0);
double areaCircle = myCircle.area()
// a circle of radius 4.0
// code that uses these objects
…
mySquare = null;
myTriangle = null;
myCircle = null;
// more code that does not use the objects created above
...


The Java constant null can be assigned to a reference.
A reference with value null refers to no object and holds no address; it is called a void reference.
45
Garbage Collection, cont
Referenced and unreferenced objects
46
Exercise 1

Develop an Object Oriented program to display the
balance of your account after each transaction. The
program must has a class named Account with two type
of constructors.
– A no-arg constructor that creates a default balance with value is 100.00.
– A constructor that update the balance based on the specified transaction,
which are either withdrawal or deposit.
– A method named getBalance() that returns the balance of the account.
Use data field balance to hold the current balance of the account.
Assign and display no transaction, transaction value is 200.00
and transaction value is –50.00 when you create the objects.
47
Exercise 2

Write an Object Oriented program to display area and
perimeter of a rectangle. Design a class named Rectangle
to represent the rectangle and the class contains:
– Two double data fields named width and height that specify the
width and height of the rectangle. The default values are 1 for
both width and height
– A no-arg constructor that creates a default rectangle.
– A constructor that creates a rectangle with the specified width
and height.
– A method named getArea() that returns the area of this rectangle.
– A method named getPerimeter() that returns the perimeter.
Assign width 4 and height 40 for the first object and width 3.5 and
height 35.9 to the second object.
48
Using Classes from the Java Library
Example 2.1 declared the Circle1 class and
created objects from the class. Often you will
use the classes in the Java library to develop
programs. You learned to obtain the current
time using System.currentTimeMillis() in
previous chapter (Primitive Data Types and
Operations), “Displaying Current Time.” You
used the division and remainder operators to
extract current second, minute, and hour.
49
The Date Class
Java provides a system-independent encapsulation of date
and time in the java.util.Date class.
Date class can be used to create an instance for the current
date and time

To return the date and time as a string its toString method is
used.
The + sign indicates
public modifer
java.util.Date
+Date()
Constructs a Date object for the current time.
+Date(elapseTime: long)
Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String
Returns a string representing the date and time.
+getTime(): long
Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void
Sets a new elapse time in the object.
50
The Date Class Example
For example, the following code
java.util.Date date = new java.util.Date();
System.out.println(date.toString());
displays a string like
Mon Jul 20 12:55:57 MYT 2009
51
The Random Class
You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0). A more useful
random number generator is provided in the java.util.Random
class.
java.util.Random
+Random()
Constructs a Random object with the current time as its seed.
+Random(seed: long)
Constructs a Random object with a specified seed.
+nextInt(): int
Returns a random int value.
+nextInt(n: int): int
Returns a random int value between 0 and n (exclusive).
+nextLong(): long
Returns a random long value.
+nextDouble(): double
Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float
Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean
Returns a random boolean value.
52
The Random Class Example
If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following
code creates two Random objects with the same seed 3.
Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
53
Instance Variables, and Methods
Instance variables belong to a specific instance.
• There is a separate copy for every object
created.
Instance methods are invoked by an instance of
the class.
54
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.
• only exists one copy no matter how many
objects create
• For example, to hold the grand total of
anything
Static methods are not tied to a specific object.
Static constants are final variables shared by all the
instances of the class.
55
Static Variables, Constants,
and Methods, cont.
To declare static variables, constants, and methods,
use the static modifier.
Keyword static denote a class variable
56
17.
18.
19.
class Circle2 {
double radius;
static int numberOfObjects = 0; // Class variable
20.
21.
22.
23.
Circle2( ) {
radius = 1.0;
numberOfObjects++;
}
Circle2(double newRadius) {
radius = newRadius;
numberOfObjects++;
}
24.
25.
26.
27.
28.
double getArea( ) {
return radius * radius * Math.PI;
29.
30.
}
31.
static int getNumberOfObjects() {
return numberOfObjects; }
32.
33.
34.
}
57
Static Variables, Constants,
and Methods, cont.
Circle2 circle1 = new Circle2();
Circle2 circle2 = new Circle2(5);
instantiate
circle1
radius = 1
numberOfObjects = 2
Circle
Memory
1
radius: double
numberOfObjects: int
getNumberOfObjects(): int
+getArea(): double
UML Notation:
underline: static variables or methods
instantiate
radius
2
numberOfObjects
5
radius
circle2
radius = 5
numberOfObjects = 2
58
Static Variables, Constants,
and Methods, cont.

circle1.numberOfObjects and
circle1.getNumberOfobjects() can be replaced with
Circle1.numberOfObjects and
Circle2.getNumberOfObjects().

Syntax: ClassName.methodName(arguments) to invoke
a static method
ClassName.staticVariable.
This improves readability because the user can easily
recognise the static method and data in the class.
59
Static Variables, Constants,
and Methods, cont.


Instance variables and methods can only be used from instance
method, not from static methods, since static variables and
methods belong to the class as a whole and not to particular
objects.
Example:
static int getNumberOfObjects() {
radius = radius * radius;
return numberOfObjects;
}
* wrong because radius is instance variable, not static variable
and cannot be used in static method.
60
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.

public
The class, data, or method is visible to any class in any
package.

private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
61
package p1;
public class C1 {
public int x;
int y;
private int z;
public void m1() {
}
void m2() {
}
private void m3() {
}
}
package p2;
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
}
package p1;
class C1 {
...
}
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
}
}
package p2;
public class C2 {
can access C1
}
public class C3 {
cannot access C1;
can access C2;
}
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.
62
NOTE
An object cannot access its private members, as shown in (b).
It is OK, however, if the object is declared in its own class, as
shown in (a).
public class Foo {
private boolean x;
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert());
}
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert(foo.x));
}
}
private int convert(boolean b) {
return x ? 1 : -1;
}
}
(a) This is OK because object foo is used inside the Foo class
(b) This is wrong because x and convert are private in Foo.
63
Why Data Fields Should Be
private?
To protect data.
To make class easy to maintain.
64
Why Data Fields Should Be private?
Example: data field radius and numberOfObjects in the
Circle2 class can be modified directly (e.g.
myCircle.radius = 5).
 This is not a good practice:

– Data may be tampered. For example, numberOfObjects is to
count the number of objects created, but it may be set to an
arbitrary value (e.g. Circle2.numberOfObjects = 10).
– It makes the class difficult to maintain and vulnerable to
bugs.Suppose you want to modify the Circle2 class to ensure
that the radius is non-negative after other programs have already
used the class. You have to change not only the Circle2 class,
but also the programs that use the Circle2 class.
65
Why Data Fields Should Be private?
 Data
field encapsulation: declare the data
field as private to prevent direct
modification of properties
 Provide a get method to return the value of
the data field. (getter/accessor)
 Provide a set method to enable a private
data field to be updated (setter/mutator)
66
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier
Circle3
-radius: double
The radius of this circle (default: 1.0).
-numberOfObjects: int
The number of circle objects created.
+Circle()
Constructs a default circle object.
+Circle(radius: double)
Constructs a circle object with the specified radius.
+getRadius(): double
Returns the radius of this circle.
+setRadius(radius: double): void
Sets a new radius for this circle.
+getNumberOfObject(): int
Returns the number of circle objects created.
+getArea(): double
Returns the area of this circle.
TestCircle3
Run
67
17.
18.
19.
public class Circle3 {
private double radius = 1;
private static int numberOfObjects = 0;
20.
public Circle3( ) {
numberOfObjects++;
21.
22.
}
23.
public Circle2(double newRadius) {
radius = newRadius;
numberOfObjects++;
}
24.
25.
26.
27.
public void setRadius(double newRadius ) {
radius = (newRadius >= 0) ? newRadius : 0;
28.
29.
}
30.
public static int getNumberOfObjects() {
return numberOfObjects; }
31.
32.
33.
public double getArea() {
return radius * radius * Math.PI
}
34.
35.
36.
37.
}
68
Immutable Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class. If you delete the set method in
the Circle class in the preceding example, the class would be
immutable because radius is private and cannot be changed
without a set method.
A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
69
Example
public class Student {
private int id;
private BirthDate birthDate;
public class BirthDate {
private int year;
private int month;
private int day;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
70
What Class is Immutable?
For a class to be immutable, it must mark all data fields private
and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.
71
Passing Objects to Methods
 Passing
by value for primitive type value
(the value is passed to the parameter)
 Passing
by value for reference type value
(the value is the reference to the object)
TestPassObject
Run
72
Passing Objects to Methods, cont.
Stack
Space required for the
printAreas method
int times: 5
Circle c: reference
Space required for the
main method
int n: 5
myCircle: reference
Pass by value (here
the value is 5)
Pass by value
(here the value is
the reference for
the object)
Heap
A circle
object
73
Scope of Variables

The scope of instance and static variables is the entire
class. They can be declared anywhere inside a class.

The scope of a local variable starts from its declaration
and continues to the end of the block that contains the
variable. A local variable must be initialized explicitly
before it can be used.

The exception is when a data field is initialized based on
reference to another data field.
74
Scope of Variables
public class Circle {
public double find getArea() {
return radius * radius * Math.PI;
}
public class Foo {
private i;
private int j = i + 1;
}
private double radius = 1;
}
75
Scope of variables
class Foo {
int x = 0;
int y = 0;
Foo() {
}
void p() {
int x = 1;
System.out.println(“x = “ + x);
System.out.println(“y = “ + y);
}
}
76
The this Keyword
 Is
a reference to the calling object
 Use
this:
– to refer to the object that invokes the instance method.
– to refer to an instance data field.
– to invoke an overloaded constructor of the same class.
77
Serving as Proxy to the Calling Object
class Foo {
int i = 5;
static double k = 0;
void setI(int i) {
this.i = i;
}
Suppose that f1 and f2 are two objects of Foo.
Invoking f1.setI(10) is to execute
f1.i = 10, where this is replaced by f1
Invoking f2.setI(45) is to execute
f2.i = 45, where this is replaced by f2
static void setK(double k) {
Foo.k = k;
}
}
78
Calling Overloaded Constructor
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
}
this is used to invoke another constructor
public double getArea() {
return this.radius * this.radius * Math.PI;
}
}
Every instance variable belongs to an instance represented by this,
which is normally omitted
79
Array of Objects
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of
reference variables. So invoking
circleArray[1].getArea() involves two
levels of referencing as shown in the next
figure. circleArray references to the entire
array. circleArray[1] references to a
Circle object.
80
Array of Objects, cont.
Circle[] circleArray = new Circle[10];
circleArray
reference
circleArray[0]
circleArray[1]
Circle object 0
…
Circle object 1
circleArray[9]
Circle object 9
81
Array of Objects, cont.
Summarizing the areas of the circles
TotalArea
Run
82
1.
2.
3.
4.
5.
6.
public class TotalArea {
public static void main(String[] args) {
Circle3[] circleArray;
circleArray = createCircleArray();
printCircleArray(circleArray);
}
7.
8.
9.
10.
11.
12.
13.
public static Circle3[] createCircleArray() {
Circle3[] circleArray = new Circle3[10];
for (int I = 0; I < circleArray.length; i++) {
circleArray[i] = new Circle3(Math.random() * 100);
return circleArray;
}
83
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
public static printCircleArray(Circle3[] circleArray) {
System.out.println (“Radius\t\t\t\t” + “Area”);
for (int i = 0; i < circleArray.length; i++) {
System.out.println(circleArray[i].getRadius() + “\t\t” +
circleArray[i].getArea() + ‘\n’);
}
System.out.println(“-----------------”);
System.out.println(“The total areas of circles is \t” +
sum(circleArray);
}
23.
24.
25.
26.
27.
28.
29.
public static double sum(Circle3[] circleArray) {
double sum = 0;
for (int i = 0; i < circleArray.length; i++)
sum += circleArray[i].getArea();
return sum;
}
84
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides
a description of the class and let the user know how the
class can be used. The user of the class does not need to
know how the class is implemented. The detail of
implementation is encapsulated and hidden from the user.
Class implementation
is like a black box
hidden from the clients
Class
Class Contract
(Signatures of
public methods and
public constants)
Clients use the
class through the
contract of the class
85
Example: The Loan Class
Loan
-annualInterestRate: double
The annual interest rate of the loan (default: 2.5).
-numberOfYears: int
The number of years for the loan (default: 1)
-loanAmount: double
The loan amount (default: 1000).
-loanDate: Date
The date this loan was created.
+Loan()
Constructs a default Loan object.
+Loan(annualInterestRate: double,
numberOfYears: int,
loanAmount: double)
Constructs a loan with specified interest rate, years, and
loan amount.
+getAnnualInterestRate(): double
Returns the annual interest rate of this loan.
+getNumberOfYears(): int
Returns the number of the years of this loan.
+getLoanAmount(): double
Returns the amount of this loan.
+getLoanDate(): Date
Returns the date of the creation of this loan.
+setAnnualInterestRate(
Sets a new annual interest rate to this loan.
annualInterestRate: double): void
Sets a new number of years to this loan.
+setNumberOfYears(
numberOfYears: int): void
+setLoanAmount(
loanAmount: double): void
Sets a new amount to this loan.
+getMonthlyPayment(): double
Returns the monthly payment of this loan.
+getTotalPayment(): double
Returns the total payment of this loan.
Loan
TestLoanClass
Run
86
Example: The Course Class
Course
-name: String
The name of the course.
-students: String[]
The students who take the course.
-numberOfStudents: int
The number of students (default: 0).
+Course(name: String)
Creates a Course with the specified name.
+getName(): String
Returns the course name.
+addStudent(student: String): void Adds a new student to the course list.
+getStudents(): String[]
Returns the students for the course.
+getNumberOfStudents(): int
Returns the number of students for the course.
Course
TestCource
Run
87
Example: The
StackOfIntegers Class
StackOfIntegers
-elements: int[]
An array to store integers in the stack.
-size: int
The number of integers in the stack.
+StackOfIntegers()
Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int)
Constructs an empty stack with a specified capacity.
+empty(): boolean
Returns true if the stack is empty.
+peek(): int
Returns the integer at the top of the stack without
removing it from the stack.
+push(value: int): int
Stores an integer into the top of the stack.
+pop(): int
Removes the integer at the top of the stack and returns it.
+getSize(): int
Returns the number of elements in the stack.
TestStackOfIntegers
Run
88
Implementing
StackOfIntegers Class
elements[capacity – 1]
.
.
.
elements[size-1]
top
.
.
.
capacity
size
elements[1]
elements[0]
bottom
StackOfIntegers
89
Note to Instructor
You can now cover Chapter 8, “Strings and
Text I/O,” or Chapter 12, “GUI Basics.”
90
Optional
GUI
Creating Windows Using the
JFrame Class
 Objective:
Demonstrate using classes from
the Java library. Use the JFrame class in the
javax.swing package to create two frames;
use the methods in the JFrame class to set the
title, size and location of the frames and to
display the frames.
TestFrame
Run
91
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true); JFrame
frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
Declare, create,
and assign in one
statement
frame1 reference
: JFrame
title:
width:
height:
visible:
92
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true); JFrame
frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
Set title property
: JFrame
title: "Window 1"
width:
height:
visible:
93
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible:
Set size property
94
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
Set visible
property
95
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
Declare, create,
and assign in one
statement
: JFrame
title:
width:
height:
visible:
96
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width:
height:
visible:
Set title property
97
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width: 200
height: 150
visible:
Set size property
98
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width: 200
height: 150
visible: true
Set visible
property
99
Exercise 3
 Write
an Object Oriented program that asks
a user to enter the distance of a trip in miles,
the miles per gallon estimate for the user’s
car, and the average cost of a gallon of gas.
Calculate and display the number of gallons
of gas needed and the estimated cost of the
trip.
100