Chapter 6 - A First Look at Classes

Download Report

Transcript Chapter 6 - A First Look at Classes

Chapter 6
A First Look at Classes
Contents
1. Classes and objects
2. Instance Fields and Methods
3. Constructors
4. Overloading Methods and Constructors
5. Scope of Instance Fields
6. Packages and import Statements
7. Focus on Object-Oriented Design: Finding the
Classes and Their Responsibilities
2
1. Classes and Objects



Procedures typically operate on data items that
are separate from the procedures.
Procedural programming is centered on
creating procedures.
Object oriented programming is centered on
creating objects.

An object is a software entity that contains data and
procedures.


Data: Fields
Procedures: Methods
3
1. Classes and Objects



An object's fields are called attributes.
A class is the blueprint for an object. It specifies
the fields and methods a particular type of
object has.
From the class, one or more objects may be
created.
4
1. Classes and Objects



Object oriented programming addresses the
problem of code/data separation through:

Encapsulation

Data Hiding
Encapsulation refers to the combining of data
and code into a single object.
Data hiding refers to an object's ability to hide
its data from code that is outside the object.


Only the object's methods may directly access and
make changes to the object's data.
An object hides its data, but allows outside code to
access its methods.
5
1. Classes and Objects

Object reusability


An object is not a stand-alone program, but is used
by programs that its services.
An everyday example of an object

Your alarm clock: An object





The current second (0-59)
The current minute (0-59)
The current hour (1-12)
The time the alarm is set for (a valid hour and
minute)
Whether the alarm is on or off (“on” or “off”)
6
1. Classes and Objects

Fields are merely data values that define the
state of the alarm clock is currently in.



The user cannot directly manipulate these fields
because they are private.
To change a field's value, we must use one of the
object's methods.
Some of the alarm clock object's methods

Set time

Set alarm time

Turn alarm on

Turn alarm off
These methods can be activated
by users, who are outside the alarm clock.
They are public methods.
7
1. Classes and Objects

The alarm clock also has private methods, which
are parts of the object's private, internal workings.



External entities (such as you, the user of the alarm
clock) do not have directly access to the alarm clock's
private methods.
The object is designed to execute these methods
automatically and hide the details from you.
Some of the alarm clock object's private methods

Increment the current second

Increment the current minute

Increment the current hour

Sound alarm
8
1. Classes and Objects



Before an object is created, it must be designed by a
programmer.
The programmer determines the fields and the methods
that are necessary, and then creates a class.
Think of a class as a “blueprint” that objects may be
created from.



A class is not an object, but it is a description of an
objects.
When the program is running, it can use the class to
create, in memory, as many objects as needed.
Each object that is created from a class is called an
instance of the class.
9
1. Classes and Objects
The Insect class describes
the fields and methods
that a particular type of
object may have.
housefly
object
The housefly object is an
instance of the Insect class. It
has the fields and methods
described by the Insect class.
mosquito
object
The mosquito object is an
instance of the Insect class. It
has the fields and methods
described by the Insect class.
Insect
class
All of the objects that are created from the same class
will have the fields ad methods described by the class.
10
Objects versus Primitive
Variables

Java primitive data types: byte, short,
int, long, char, float, double,
boolean


Primitive variables are storage locations in the
computer's memory.
A primitive data type is called “primitive” because a
variable created with a primitive data type has no
built-in capabilities other than storing a value.
11
Objects versus Primitive
Variables

String class allows you to create String
objects

In addition to storing strings, String object s have
numerous methods that perform operations on the
strings they hold.
String name = “Peter”;
A String object
The name variable
holds the address of
a String object.
address
“Peter”
StringSize = name.length();
12
Building a Simple Class Step by
Step

Write a class named Rectangle. Each object that is
created from the Rectangle class will be able to
hold data about a rectangle.


A Rectangle object will have the following fields

length: Hold the rectangle's length

width: Hold the rectangle's width
The Rectangle class will also have the following
methods

setLength: Store a value in an object's length field

setWidth: Store a value in an object's width field

getLength: Return the value in an object's length13field
Building a Simple Class Step by
Step



getWidth: Return the value in an object's width
field.
getArea: Return the area of the rectangle.
When designing a class it is often helpful to
draw a UML diagram.


UML stands for United Modeling Language.
It provides a set of standard diagrams for
graphically depicting object oriented systems.
14
UML Diagram for a Class

The general layout of a UML diagram for a
class:

The diagram is a box that is divided into three
sections.



The top section is where you write the name of
the class.
The middle section holds a list of the class's
fields.
The bottom section holds a list of the class's
methods.
15
UML Diagram for a Class

UML diagram for the Rectangle class
Rectangle
length
width
setLength()
SetWidth()
GetLength()
GetWidth()
getArea()
16
Writing the Code for a Class


Create a file named Rectangle.java
In the Rectangle.java file, we start by writing a
general class skeleton as follows
public class Rectangle
{
}

The public access specifier indicates that the
class will be publicly available to code outside 17
the Rectangle.java file.
Writing the Code for the Class
Fields

We will write the code for the class's two fields
width and length. We use variables of the
double data types.
public class Rectangle
{
private double length;
private double width;
}

18
Writing the Code for the Class
Fields

Access specifier


private: When the private access specifier is
applied to a class member, the member cannot be
accessed by the code outside the class. The
member can be accessed only by methods that are
members of the same class.
public: When the public access specifier is
applied to a class member, the member can be
accessed by the code inside the class or outside.
19
Writing the setLength Method
public class Rectangle
{
private double length;
private double width;
/** The setLength method stores a value in
the length field.
@param len The value to store in length.
*/
public void setLength(double len)
{
length = len;
}
}
20
Using Rectangle Class
21
Using Rectangle Class
22
Using Rectangle Class
23
Using Rectangle Class
24
Using Rectangle Class

Rectangle box = new Rectangle();
A Rectangle object
The box variable
holds the address of
a Rectangle bject.

box.setLength(10.0);
The box variable
holds the address of
a Rectangle bject.

address
address
box.setWidth(20.0);
The box variable
holds the address of
a Rectangle bject.
address
length
0.0
width
0.0
A Rectangle object
length
10.0
width
0.0
A Rectangle object
length
width
10.0
20.0
25
Accessor and Mutator Methods




It is a common practice to make all of a class's fields
private and to provide public methods for accessing
and changing those fields.
A method that gets a value from a class's field but
does not change it is known an accessor method
(getter).
A method that stores a value in a field or changes the
value of a field is known as a mutator method (setter).
In the Rectangle class

getLength, getWidth: accessor methods

setLength, setWidth: mutator methods
26
Avoiding Stale Data


In the Rectangle class, the getArea method
returns the result of a calculation.
The area of the rectangle is not stored in a field.
Why?


The area is not stored in a field because it could
potentially become stale.
When the value of an item is dependent on other
data and that item is not updated when the other
data is changed, it is said that the item has become
stale.
27
Avoiding Stale Data


If the area is stored in a field, the value of this
field becomes incorrect as soon as either the
length or width fields changed.
When designing a class, you should take care
not to store in a field calculated data that can
potentially become stale.

Instead, provide a method that returns the result of
the calculation.
28
Showing Access Specification in
UML Diagrams

In a UML diagram,


A – character before a member name indicates that
it is private.
A + character before a member name indicates that
it is public.
Rectangle
- length
- width
+
+
+
+
+
setLength()
setWidth()
getLength()
getWidth()
getArea()
29
Data Type and Parameter
Notation in UML Diagrams

The UML diagram also provides notation that
you may use to indicate

Data types of fields, methods

Parameter variables

Return type of a method
Rectangle
- length: double
- width: double
+
+
+
+
+
setLength(len: double): void
setWidth(w: double): void
getLength(): double
getWidth(): double
getArea(): double
30
Layout of Class Members

Typical layout of class members
public class ClassName
{
Field declarations
Methods definitions
}
31
Checkpoint

6.3

6.5

6.6

6.7

6.8

6.9
32
2. Instance Fields and Methods



Each instance of a class has its own set of
fields, which are known as instance fields or
instance variables.
You can create several instances of a class and
store different values in each instance's fields.
The methods that operate on an instance of a
class are known as instance methods.

Instance methods do not have the keyword static
in their headers.
33
2. Instance Fields and Methods
Rectangle kitchen = new Rectangle();
Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();
The box variable
holds the address of
a Rectangle bject.
The bedroom variable
holds the address of
a Rectangle bject.
The den variable
holds the address of
a Rectangle bject.
address
address
address
length
0.0
width
0.0
length
0.0
width
0.0
length
0.0
width
0.0
A Rectangle
object
A Rectangle
object
A Rectangle
object 34
2. Instance Fields and Methods
kitchen.setLength(10.0);
kitchen.setWidth(14.0);
bedroom.setLength(15.0);
bedroom.setWidth(12.0);
den.setLength(20.0);
den.setWidth(30.0);
The kitchen variable
hold the address of
a Rectangle object.
address
Length
width
20.0
30.0
A Rectangle
object
The bedroom variable
hold the address of
a Rectangle object.
address
Length
width
20.0
30.0
A Rectangle
object
The den variable
holds the address of
a Rectangle bject.
address
Length
width
20.0
30.0
A Rectangle
35
object
Checkpoint

6.10 Assume that r1 and r2 are variables that
reference Rectangle objects, and the
following statements are executed:
r1.setLength(5.0);
r2.setLength(10.0);
r1.setWidth(20.0);
r2.setWidth(15.0);
Fill in the boxes in the figure that represent each object's
length and width fields.
36
Checkpoint
r1
r2
address
address
length
0.0
width
0.0
length
0.0
width
0.0
A Rectangle
object
A Rectangle
object
37
Checkpoint
r1.setLength(5.0);
r2.setLength(10.0);
r1.setWidth(20.0);
r2.setWidth(15.0);
r1
r2
address
address
length
0.0
5.0
width
20.0
0.0
length
10.0
0.0
width
15.0
0.0
A Rectangle
object
A Rectangle
object
38
3. Constructors

A constructor



Has the same name as the class.
A method that is automatically called when an
instance of a class is created.
Performs initialization or setup operations



Storing initial values in instance fields.
It is called a constructor because it helps construct
an object.
The constructor's header does not specify a return
type.
39
3. Constructors

Write a constructor in the class Rectangle:

The constructor has the name Rectangle.

The constructor has two arguments



The length of the rectangle
The width of the rectangle
Two arguments are then assigned to the length
and width fields.
40
3. Constructors

This constructor accepts two arguments.
41
3. Constructors


Constructor's header does not specify a return
type – not even void.
The method header for a constructor
AccessSpecifier ClassName(Parameters … )

Showing Constructors in a UML Diagram
Rectangle
- length: double
- width: double
+
+
+
+
+
+
Rectangle(len: double, w: double)
setLength(len: double): void
setWidth(w: double): void
getLength(): double
getWidth(): double
getArea(): double
42
3. Constructors
43
Uninitialized Local Reference
Variables


Reference variables can be declared without
being initialized.
Rectangle box;

Does not create a Rectangle object.

Only declares a variable named box.

Does not reference to any Rectangle object.


It is an uninitialized local reference variable.
box = new Rectangle(7.0, 14.0);

Creates a Rectangle object in memory.

box references to this object.
44
Uninitialized Local Reference
Variables
Rectangle box;
box = new Rectangle(7.0, 14.0);
Rectangle box = new Rectangle(7.0, 14.0);

Be careful when using uninitialized reference
variables:

Reference variables must be initialized or assigned
45
a value before they can be used.
The Default Constructor


When an object is created, its constructor is
always called.
If we do not write a constructor


Java automatically provides one. It is known as
default constructor.
The default constructor

Does not accept arguments

Sets all object's numeric fields to 0

Sets boolean fields to false.

Sets fields that are reference variables to null.
46
The Default Constructor

We wrote no constructor for the Rectangle
class
Rectangle r = new Rectangle();
// Calls the default constructor

Now we wrote our own constructor for the
Rectangle class
Rectangle r = new Rectangle(); // Error!

Java does not provide the default constructor.

We must call the constructor we wrote.
47
No-Argument Constructor



A constructor that does not accept arguments is
known as a no-argument constructor.
The default constructor is a no-argument
constructor.
We can write our own no-argument constructor.
public Rectangle()
{
length = 1.0;
width = 1.0;
}
Rectangle r = new Rectangle();
● Calls the no-argument constructor
48
The String Class Constructor

The String class has a constructor.

Accepts a string literal as its argument.
Uses the string literal to initialize the String object.
String name = new String(“Pham Dai Xuan”);


Java provides the shortcut notation for creating
and initializing String objects.
String name = “Pham Dai Xuan”;
49
Checkpoint

6.11 How is a constructor named?


A constructor must have the same name as the
class.
6.12 What is a constructor's return type?

A constructor does not have a return type.
50
Checkpoint


6.13 Assume that the following is a constructor,
which appears in a class:
ClassABC(int number)
{
item = number;
}
a) What is the name of the class ?
ClassABC
b) Write a statement that create an object and passes
the value 25 as an argument to the constructor.
ClassABC abc = new ClassABC(25);
51
Overloading Methods and
Constructors

Problem: Write a Java class that has seven
methods
1) Calculate the sum of two integer numbers.
2) Calculate the sum of two double numbers.
3) Calculate the sum of an integer number and a
double number.
4) Calculate the sum of a double number and an
integer number.
5) Combine two strings.
6) Combine a double with a string
7) Combine a String with a double
52
Overloading Methods and
Constructors

UML class diagram
Addition
+
+
+
+
+
+
+
addInt(num1: int, num2: int): int
addDouble(num1: double, num2: double): double
addIntDouble(num1: int, num2: double): double
addDoubleInt(num1: double, num2: int): double
addString(str1: String, str2: String): String
addDoubleString(num: double, str: String): String
addStringDouble(str: String, num: double): String
53
Overloading Methods and
Constructors
54
Overloading Methods and
Constructors
55
Overloading Methods and
Constructors
56
Overloading Methods

The Addition class is not easy to use.


We have to choose the right method for each case.
How about the + operator in Java

10 + 2

5.3 + 7.3

2 + 5.3

3.4 + 2

“Hello “ + “world!”

“10.5 “ + “kg”

“Weight (kg): “ + 20.5
We use the same + operator as long as
their operands are different.
57
Overloading Methods

In Java, two or more methods in a class may
have the same name as long as their
parameter lists are different.



Overloading methods
When a method is overloaded, it means that
multiple methods in the same class have the
same name, but use different types of
parameters.
Method overloading is used when several
different ways to perform the same operation.
58
Overloading Methods

UML class diagram
Addition
+
+
+
+
+
+
+
add(num1: int, num2: int): int
add(num1: double, num2: double): double
add(num1: int, num2: double): double
add(num1: double, num2: int): double
add(str1: String, str2: String): String
add(num: double, str: String): String
add(str: String, num: double): String
59
Overloading Methods
60
Overloading Methods
61
Overloading Methods
62
Overloading Methods


Java uses a method's signature to distinguish it
from other methods of the same name.
A method's signature

The method name

The data type of the method's parameters
add(int, int)
add(String, String)
add(double, String)
add(String, double)
63
Overloading Methods



Note that the method's return type is not part of
the signature.
public String add(String str1, String str2)
{
return str1 + str2;
}
public int add(String str1, String str2)
{
return Integer.parseInt(str1) +
Integer.parseInt(str2);
}
These two methods can not be added to the same class.
64
Overloading Constructors

Constructors can be overloaded.


A class can have more than one constructors.
The rules for overloading constructors are the same
for overloading methods.
public Rectangle()
{
length = 0.0;
width = 0.0;
}

public Rectangle(int l, int w)
{
length = l;
width = w;
}
Rectangle box1 = new Rectangle();
Rectangle box2 = new Rectangle(5.0, 10.0);
65
The BankAccount Class

A bank account is simulated by an object of the
BankAccount class. The BankAccount object
allows us

To have a starting balance

To make deposits

To make withdrawals

To get the current balance
66
The BankAccount Class

UML class diagram
BalanceAccount
- balance: double
+
+
+
+
+
+
+
+
+
+
BankAccount():
BankAccount(startBalance: double):
BankAccount(str: String):
deposit(amount: double): void
deposit(str: String): void
withdraw(amount: double): void
withdraw(str: String): void
setBalance(b: double): void
setBalance(str: String): void
getBalance(): double
67