Bài giảng Phát triển phần mềm phân tán - Bài 4: Encapsulation and class building - Vũ Thị Hương Giang
21-Oct-16
Objectives
LESSON IV.
Encapsulation and Class Building
•
•
Understand the application of object oriented
principles in Java
Acquaint how to declare a class and its members
Vu Thi Huong Giang
SoICT (School of Information and
Communication Technology)
HUST (Hanoi University of Science
and Technology)
1
3
5
2
Content
Abstraction
•
Data abstraction
•
•
Abstraction hides the detailled
information about object.
Abstraction is a view or representation
of an object that includes only the
most significant attributes
–
–
–
Overview
Class and instance
Message passing
•
•
Encapsulation
–
Visibility
–
These attributes make dicstinction this
object with others.
Class building
–
–
Declaration
•
Class declaration
Class member declaration
•
Data hiding
4
Abstract data type
2. Class
•
Abstract data type = data type + operation performed
on this type
•
•
A class is the blueprint from which individual
objects are created.
A class specifies the common attributes and
operations of many individual objects all of the
same kind.
A class defines a new data type, whose values
are objects:
A class is a template for objects; it abstracts a set of
–
Every operation related to a data structure is grouped
together
–
Only possible operation are provided in the type's definition
•
•
Java allows implementing ADT in the form of classes.
A class comprises of attributes and operations.
•
ttributes
–
objects
–
An object is an instance of a class; it concretes a class.
Operations
1
21-Oct-16
Attributes and operations
Example: Class and instance
•
Attribute
Instance: a concrete object
Instance attribute: attribute that is
assigned by a concrete value
Operations:
object
behavior
Attributes:
information about
object states
–
An attribute of a class is an identified common state of
all instances of this class (i.e. set of concrete objects).
–
An attribute specifies all possible values that can be
assigned as concrete state of these of objects.
borrow
Each object maintains a private copy of each attribute
Vu Thi Huong
Giang
value
250 pages
•
Operation
Human
computer
interaction
–
An operation of a class is an identified common behavior
of all instances of this class (i.e. set of concrete objects).
The behavior operates on the class attributes and
usually derives the change of a class’ state.
countPages
Object MyBook
Class
7
3. Message passing
II. Encapsulation
•
Message passing is the only way to interact with
objects
•
Encapsulation: Prevents the code and data being
randomly accessed by other code defined outside
the class.
–
Objects communicate by sending messages
–
Objects respond to a message that is sent to them by
performing some action.
–
Group data and operations performed on these data
together in a class
–
Hide details about the class implementation from the
user.
getAuthorName
Vu Thi Huong Giang
Message sender
Message target
(Object MyBook)
10
Visibility scope
•
Scope determines the visibility of program elements with
respect to other program elements.
III. CLASS BUILDING
•
Given a class:
–
A private attribute or operation of an object is accessible by all
others objects of the same class
–
A public attribute or operation of an object is accessible by all
others objects.
X
myBook.author
getAuthorName
private
public
Vu Thi Huong Giang
1. Declaration
2. Data hiding
Object outside the class Book
Object MyBook
If an attribute or operation is declared private, it cannot be
accessed by anyone outside the class
11
12
2
21-Oct-16
Access modifier: Class’ and
members’ visibility scope
a. Class declaration
[package package-name;]
[access-modifier] class class-name
// class body
access-modifier type instance-variable-1;
static type class-variable-2; ...
•
Four visibility scopes are identified in term of
access modifiers to limit the access to the
attribute and the operation:
{
…
–
–
–
public: visible to the world (free access)
private: visible to the class only (class access)
protected: visible to the package and subclasses (only
with an inheritance relationship)
type method-name-1(parameter-list) {…} …
}
–
default (no modifier declared): visible to the package
(package access)
•
A class encapsulates following members:
–
–
–
Name
•
Example:
Variables: declare the attributes of a class
Methods: declare the operations of class
package acu.java.example;
class Account
{
•
•
Related classes can be grouped into a package
to easily control the access to these classes.
The visibility scope of a class can be explicitly
set by declaring an access modifier.
…
}
14
Example: Class and Object
b. Variable declaration
Account object of Mrs. Giang
•
Variables must be declared within a class
Operations
Attributes
withdraw
200 VND
–
–
–
Instance variables (member variables): declared
within a class + outside any method
Class variables : declared within a class, outside any
method, with the static keyword
Local variables: declared inside methods, constructors
or statement blocks (invisible outside them)
deposit
100
VND
Vu Thi Huong
Giang
owner
withdraw
owner
balance
1.000.000
VND
check balance
class class-name
{
[access-modifier] type instance-variable-1;
static datatype class-variable-1; ...
…
deposit
Account object of Mr. Tuan
datatype method-name-1(parameter-list)
{
balance
withdraw
100 VND
datatype local-variable-1;
…
Nguyen
Manh Tuan
deposit
}
…
check balance
200
owner
VND
}
2.000.000
VND
balance
Class Account
check balance
16
15
Example: Class and variables
Variable creation
•
Declaration of a class with two
variable members:
Method declaration
Variable declaration
datatype var1 = new datatype();
class Account{
•
A variable var1 is declared to refer to
the object of class datatype.
Account1 acct1;
String owner;
acct1
withdraw
owner
long balance;
…
}
// acct1 represents nothing
•
After the assignment, the reference
variable var1 contains the address of
a concrete datatypeobject that was
created in memory.
class Account1{
private String owner;
deposit
private long balance;
balance
…
}
acct1
= new Account1();
check balance
Account1
Object
Can you show the difference between
these 2 declarations ?
acct1
// acc1 refers to an Account1 object
Use private modifier for declaring the
concrete state of an object.
17
Class Account
18
3
21-Oct-16
Example: instance variable creation
Example: instance variable creation
Account object of Mrs. Giang
Account object of Ms. Giang
Variable declaration
•
New Account objects are
created and new values are
assigned to theirs 2 variables:
Account acc1 = new Account();
acc1.name =
“Vu Thi Huong Giang”;
owner: Vu Thi Huong Giang
balance: 2.000.000 VND
owner: Vu Thi Huong Giang
balance: 2.000.000 VND
acc1.balance = “2000000”;
Account acc2 = new Account();
acc2.name = “Nguyen Manh Tuan”;
acc2.balance = “1000000”;
owner
Account object of Mr. Tuan
Account object of Mr. Tuan
balance
each object has its own data space
changing the value of a variable in
one object doesn’t change it for
other
owner: Nguyen Manh Tuan
balance: 1.000.000 VND
owner: Nguyen Manh Tuan
balance: 1.000.000 VND
Class Account
19
Class (static) variables
Static variable
Account object of Ms. Giang
class Account {
// Member variable
•
•
Class variable: declared with the static keyword
Memory space for a class variable is created
when the class is first referenced
It holds the same value for all objects
instantiated from this class changing the value
of a static variable in one object changes it for all
others
Declaration format:
[access-modifier] static data-type
member-variable-name;
String name; // Account name
long balance; // Balance
static float interest;//Deposit rate
}
owner: Vu Thi Huong Giang
balance: 2.000.000 VND
•
class AccountClassUsage{
public static void main(String[] args) {
Account.interest=0.05f;
Account giang= new Account();
Acount tuan = new Account();
giang.interest=0.04f;
tuan.interest=0.03f;
}
interest 0.05f 0.04f 0.03f
Owned by each
object
•
•
Shared
among all
objects
Account object of Mr. Tuan
Reference format:
owner: Nguyen Manh Tuan
balance: 1.000.000 VND
}
class-name.member-variable-name;
object-name.member-variable-name;
Static variable cannot be used
within a non-static method.
interest 0.05f 0.04f 0.03f
21
22
c. Method declaration
c. Method declaration
•
Syntax
•
A Java method has two parts:
[access-modifier] return-type name(parameter-list) {
–
Declaration:
// body
•
Specifies the name of the method, its return
[return return-value;]
}
type and its formal parameters (if any)
•
Is used to hide the internal data structures of
a class, as well as for their own internal use.
where:
–
return-type: type of values returned by the
method (void if a method does not return any
value)
–
Implementation:
•
•
•
Specifies a collection of statements that are
grouped together to perform an operation.
These statements are executed when a
method is called.
It is through the implementation of the
method that the state of an object is changed
or accessed.
–
–
name: name of the method
parameter-list: sequence of type-identifier lists
separated by commas
–
return-value: what value is returned by the
method.
23
24
4
21-Oct-16
Example: Method declaration and
implementation
Signature
•
The type of a variable assigned the
value returned by a method must
agree with the return type of this
method:
Method declaration
Variable declaration
•
The signature of a method consists of
–
The method's name
–
A list of parameter types, in which the
number and the order of parameters are
respected.
class Account1{
withdraw
private String name;
private long balance;
// deposit money
owner
•
Example: the signature of the
following method is deposit(long)
public void deposit(long money)
balance += money;
}
{
deposit
Signature
balance
// Check the account balance
public long checkBalance()
{
return balance;
}
public void deposit(long amount) {
check balance
…
}
•
//body
Parameter type
Member variables can be used
anywhere inside the class.
Class Account
}
Method name
25
26
Method with a variable-length
argument
Static method
static return-type name(parameter-list) { … }
Several restrictions:
•
Declaring a variable-length parameter allows passing
many values of the same data type.
•
–
can only call static methods
–
No explicit number and order of arguments is declared
•
Class name.method_name(argument);
–
You may not pass the value to a variable-length argument.
•
Object name.method_name(argument);
Class Account
•
•
The passed arguments are treated as an array.
Syntax:
–
must only access static variables
withdraw
check
balance
modifier return-type method-name
interest
deposit
class Account
// Member variable
..
static float interest;//Dep
public static void setInter
{
(data-type variable-length-parameter) {
set in
// body
interest
= pInterest;
return return-value;
}
}
}
er: Nguyen Manh Tuan
nce: 1.000.000 VND
Account.setInterest(0.05f);
Account tuan new Account();
=
tuan.setInterest(0.04f);
27
28
Account object of Mr. Tuan
Example
2. Data hiding
public class VariableLengthArgumentUsage {
•
A class provides data hiding
public static double average( double... numbers ) {
double total = 0.0;
–
Data is in a unique scope; access controlled
with public, private, protected keywords
for
total += d;
return total / numbers.length;
( double d : numbers )
–
Data is accessed through public methods; a
collection of the signatures of public
methods of a class is called interface.
}
Avoid illegal modification of attributes
public static void main(String[] args) {
double d[] = {10.0, 20.0, 30.0, 40.0, 50.0};
System.out.printf("Mean value of this array is");
Public Interface
System.out.printf(" %.1f\n", average(d[0], d[1], d[2],
d[3], d[4]));
Method
call
Internal
working
}
}
29
30
5
21-Oct-16
Quiz 1 – variable and method
declaration
Quiz 1 – solution
public class Media
{
public void setCategory
(String category)
this.category category;
•
Declare the class Media describing media
products such as book, that has following
attributes and operations
private String title;
private String category;
private float cost;
public String getTitle()
return title;
{
=
}
{
public void setCost
(float cost)
this.cost cost;
–
–
–
–
–
Title
Category
Price
{
}
=
public String getCategory()
{
}
Show the title, price, category of a media product
Set a title, price, category for a media product
return category;
public void setTitle
(String title)
this.title title;
}
{
public float getCost()
{
=
return cost;
}
}
}
31
32
Quiz – static variable and static
method
Quiz 2 - Solution
public class Media {
private String title;
private String category;
private float cost;
2. In the class Media:
–
Declare the product distributor as a static variable
–
Declare and implement the static method that allows changing the
distributor of all media products.
static String distributor;
3. In the class Media:
–
Declare and implement a method for displaying information about
a concrete media product. Explain which attributes can be
displayed by this method and why.
Declare and implement a method with variable-length argument
for displaying all information about a concrete media product.
// ... implementation of methods as in the solution of Quiz 1
public static void setDistributor(String dist) {
–
distributor = dist;
}
}
4. Write a program that
–
calls the static method using the class name
–
calls an instance of the method with/without variable-length
argument
33
34
Quiz 3 - Solution
Quiz 4 - solution
public void displayInstanceInfo() {
public static void displayInstanceInfo
(String... values) {
public class MediaClassUsage {
System.out.println("Information about
concrete media product: ");
a
public static void main(String[] args) {
// static reference of variable
System.out.println("Title: "+ title);
System.out.println("Information
about the media product: ");
System.out.println("Distributor:
// create concrete media product
Media media = new Media();
" + Media.distributor);
System.out.println("Category:"
+
a
category);
System.out.println("Price:"
+
cost);
for ( String v : values )
media.setTitle("Vivaldi: The Four Seasons");
media.setCategory("CD"); media.setCost((float) 14.38);
media.setDistributor("Amazon");
// can not access to static variable
System.out.print(v);
}
}
// static method call
public static void displayStaticInfo() {
Media.displayStaticInfo();
System.out.println("Distributor:
" +
// call of instance method without variable-length args
media.displayInstanceInfo();
distributor);
// can not access to instance variable
// call of instance method with variable-length args
}
media.displayInstanceInfo("Title: ", media.getTitle(), "\n",
"Category: ", media.getCategory(),"\n",
"Price: ", Float.toString(media.getCost()),"\n",
"Distributor: ", media.distributor);
}
35
36
}
6
21-Oct-16
Review
Review
•
Data abstraction:
•
Data abstraction:
–
the class is the abstract data type, defining the representation of and
operations on objects of the type.
–
the class is the abstract data type, defining the
•
Encapsulation:
representation of and operations on objects of the type.
–
Class encapsulates objects
•
Encapsulation:
–
Object encapsulates data and implementation
•
•
Visibility: To control the access to a class and to its members,
we can use
–
Class encapsulates objects
–
Object encapsulates data and implementation
–
Access modifiers: public, private, protected, default
•
•
•
Private: for hidden members
Public: for interface members
Protected: for inheritance (discuss later)
–
Package scope: members of all classes in a package that have default
modifiers are visible throughout the package
Class building
–
Variable declaration
–
Method declaration
37
38
Review
•
Visibility: To control the access to a class and to
its members, we can use
–
Access modifiers: public, private, protected, default
•
•
•
Private: for hidden members
Public: for interface members
Protected: for inheritance (discuss later)
–
Package scope: members of all classes in a package that
have default modifiers are visible throughout the
package
•
Class building
–
Variable declaration
–
Method declaration
39
7
Bạn đang xem tài liệu "Bài giảng Phát triển phần mềm phân tán - Bài 4: Encapsulation and class building - Vũ Thị Hương Giang", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_phat_trien_phan_mem_phan_tan_bai_4_encapsulation_a.pdf