Chapter 6 Chapter 6 A First Look at Classes 2 Contents 1 Classes and objects 2 Instance Fields and Methods 3 Constructors 4 Overloading Methods and Constructors 5 Scope of Instance Fields 6 Packages a.
Trang 1Chapter 6
A First Look at Classes
Trang 21 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
Trang 31 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
Trang 41 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
Trang 51 Classes and Objects
Object oriented programming addresses the
problem of code/data separation through:
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
Trang 61 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)
Trang 71 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
These methods can be activated
by users, who are outside the alarm clock.
They are public methods.
Trang 81 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
Trang 91 Classes and Objects
Before an object is created, it must be designed by a
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.
Trang 101 Classes and Objects
Insect class
housefly object
mosquito
The Insect class
describes
the fields and methods
that a particular type of
object may have.
The Insect class
describes
the fields and methods
that a particular type of
object may have.
The housefly object is an instance of the Insect class It has the fields and methods described by the Insect class.
The mosquito object is an instance of the Insect class It
Trang 11A 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
Trang 12Objects 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”;
address “Peter”
A String object The name variable
holds the address of
a String object.
Trang 13A 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
Trang 14Building 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 Unified Modeling Language
It provides a set of standard diagrams for
Trang 15UML Diagram for a Class
The general layout of a UML diagram for a class:
The diagram is a box that is divided into three
Trang 16UML Diagram for a Class
UML diagram for the Rectangle class
Rectangle length width
setLength() SetWidth() GetLength() GetWidth() getArea()
Trang 17Writing 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
Trang 18Writing 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;
Trang 19Writing 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
Trang 20Writing 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)
{
Trang 21Using Rectangle Class
Trang 22Using Rectangle Class
Trang 23Using Rectangle Class
Trang 24Using Rectangle Class
Trang 25Using Rectangle Class
Rectangle box = new Rectangle();
box.setLength(10.0);
box.setWidth(20.0);
address
length width
A Rectangle object The box variable
holds the address of
a Rectangle object.
0.0 0.0
address length
width
A Rectangle object The box variable
holds the address of
a Rectangle bject.
10.
0 0.0
address length
width
A Rectangle object The box variable
holds the address of
a Rectangle object.
10.
0 20.
0
Trang 26Accessor 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
Trang 27Avoiding 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.
Trang 28Avoiding 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
Trang 30Data Type and Parameter Notation in UML Diagrams
The UML diagram also provides notation that you may use to indicate
Data types of fields, methods
Trang 31Layout of Class Members
Typical layout of class members
public class ClassName
{
}
Field declarations
Methods definitions
Trang 332 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
Trang 342 Instance Fields and Methods
Rectangle kitchen = new Rectangle();Rectangle bedroom = new Rectangle();Rectangle den = new Rectangle();
address
length width
A Rectangle object
The box variable holds the address of
a Rectangle bject.
0.0 0.0
address length
width
The bedroom variable holds the address of
a Rectangle bject.
0.0 0.0
A Rectangle object
Trang 350
14.
0 The bedroom
variable hold the address of
a Rectangle object.
The kitchen variable hold the address of
a Rectangle object.
Trang 366.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.
Trang 37Checkpoint
address
length width
0.0 0.0
address length
width
0.0 0.0
A Rectangle object
A Rectangle object r1
r2
Trang 380.0 0.0
A Rectangle object
20.
0
Trang 393 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
Trang 403 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 lengthand width fields
Trang 413 Constructors
This constructor accepts two arguments
Trang 423 Constructors
Constructor's header does not specify a return
type – not even void
The method header for a constructor
Trang 433 Constructors
Trang 44Uninitialized 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);
Trang 45Uninitialized 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 a value before they can be used
Trang 46The 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
Trang 47The 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
Trang 48No-Argument Constructor
A constructor that does not accept arguments is
known as a no-argument constructor.
The default constructor is a no-argument
Trang 49The 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”;
Trang 506.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
Trang 51b) Write a statement that create an object and
passes the value 25 as an argument to the
constructor
Trang 52Overloading 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
Trang 54Overloading Methods and
Constructors
Trang 55Overloading Methods and
Constructors
Trang 56Overloading Methods and
Constructors
Trang 57Overloading Methods
The Addition class is not easy to use
We have to choose the right method for each
We use the same + operator as long as
their operands are different.
Trang 58Overloading 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
Trang 60Overloading Methods
Trang 61Overloading Methods
Trang 62Overloading Methods
Trang 63Overloading 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)
Trang 65Overloading Constructors
Constructors can be overloaded
A class can have more than one constructors
The rules for overloading constructors are the same for overloading methods
Rectangle box1 = new Rectangle();
Rectangle box2 = new Rectangle(5.0, 10.0);
Trang 66The 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
Trang 67The 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
Trang 68The BankAccount Class
Trang 69The BankAccount Class
Trang 70The BankAccount Class
Trang 71The BankAccount Class
Trang 72The BankAccount Class
Trang 73The BankAccount Class
Trang 745 Scope of Instance Fields
A variable's scope is the part of a program where the variable may be accessed by its name
Location of a variable's declaration determines
the variable's scope
Instance fields can be accessed by any instance method in the same class as the field
If the instance field is declared with the public
Trang 75However, we can have a local variable or a
parameter variable with the same name as a field
The name of the local variable or parameter
variable shadows the name of the field
Trang 76For example, assume that the Rectangle
class's setLength method had been written in
the following manner:
public void setLength(double len)
{
double length; // local variable
length = len; // length : local
Trang 77Checkpoint
6.14 Is it required that overloaded methods have different return values, different parameter lists, or both?
Different parameter lists
6.15 What is a method's signature?
A method's signature is used to distinguish it from other methods of the same name
A method's signature consists of
Method name
Data types of the method's parameters in order
Trang 78Look at the following class:
public class Checkpoint
Trang 79Checkpoint
What will the following code display?
Checkpoint cp = new Checkpoint();
cp.message(“1”);
cp.message(1);
This is the 2nd version of the method
This is the 1st version of the method
Trang 806.17 How many default constructors may a class have?
1
Trang 81Packages and import Statements
The classes in the Java API are organized into
packages An import statement tells the
compiler which package a class is located in
A package is simply a group of related classes
Each package has a name
We have to import an API class in order to use it