您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 21

Encapsulation

An important principle of object-oriented analysis and design is how both the attributes (data) and operations of objects are modeled together. This makes object-oriented modeling more natural than many other modeling techniques, since it allows a modeler to model the things we know and wish to record about a class of objects (e.g. bank account balance) alongside the actions we need to be able to perform on such objects (e.g. open new account, deposit money, withdraw money, set up standing order). The term encapsulation is used to describe this feature of object technologies.

Below is the Java code for a simple, bank account class of objects called CurrentAccount. The details of the Java are not important for this example, however what is hopefully clear is the way both the data (balance) and the operations (add coins, remove coins) are modelled together in the single class CurrentAccount.

 

Comments in Java code

Note that any line beginning with "//" is a Java comment. The whole line is ignored by Java, and in most cases comments are solely added to program listings for the important purpose of presenting useful comments to help a human understand the program.

Thus lines such as "// current balance of CurrentAccount" do not effect the class behaviour, but does make the Java code much easier to understand. 

class CurrentAccount{
// current balance of CurrentAccount
private float balance;
void CurrentAccount()
{ //create new bank account with 0 balance
...}
void debit( float amount )
{ // subtract value of coins from balance
// error if try to take out more than balance
...}
float getBalance ()
{ // return value of balance
...}
float setBalance ( float amount )
{ // return value of balance
// (maybe with additional behaviour)
...}
} // end of class CurrentAccount

Notice for this example, how there are separate ‘get’ and ‘set’ methods, called accessor methods that control access to the balance attribute. Thus encapsulated in this class is the feature that the value of the balance attribute is different depending on the operation wishing to retrieve the value. In the example, the balance for normal transactions would be whatever value is stored in the object. However, since a charge is made when an account is closed, the value of the balance attribute returned by the operation getBalancee() has a charge deducted from it.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg