您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 7

Defining a more complex Class

Considering a library records system, we shall define a class for text items as follows:

class TextItem
{
  // variables
  String title;
  int numPages;
  String shelfMark;
  boolean onLoan;
  int daysLate;

  // methods
  void TextItem( String itemTitle,int itemNumPages, 
                  String itemShelfMark) 
  { // method implementation }

  String getTitle() { // method implementation 
  }

  int getNumPages() { // method implementation
  }

  String getShelfMark() { // method implementation
  }

  boolean getLoanStatus() {// method implementation
  }

  void setLoanStatus(boolean newLoanStatus) 
  { // method implementation 
  }

  int getDaysLate() { // method implementation
  }

  void setDaysLate(int newDaysLate)
  {//method imlementation
  }

  double getFine() { // method implementation 
  }

  void informBorrowerOfFine( <args> ) 
  {// method  implementation 
  }

  }

For now the implementation of the methods has been replaced with comments.

As can be seen from the class definition, the class defines 5 variables:

title
numPages
shelfMark
onLoan
daysLate
These correspond to attributes identified during analysis and modelling. However, another attribute was also identified, which has not been implemented as a variable in this class. That other attribute was the fine due on a TextItem object. 

A general rule of thumb, when performance is not a major issue, is never to store a value that can be calculated when it is needed. If we assume that the fine for a TextItem is always 0.05 pounds for each day late, since we have the variable daysLate already stored as a variable, we can always calculate the fine when needed.

A method that needs to find out the fine is the getFine() method, which we might implement as follows:

double getFine()
{
  return (0.05 * daysLate);
}
This method calculates the fine and returns the result of the calculation as a reply.
 
Implementation observation
Not every attribute identified in analysis and modelling is implemented as a variable.
If a value can be calculated form other variables, then a get() method is all that is needed ?the implemented variable will be set via changes to the variables that make up its calculation.


This class of objects has behaviour. For example, the method informBorrowerOfFine(<args>) may result in the retrieval of a borrower's address, and a letter being sent to them, if the fine reaches a certain amount (say 5.00 pounds).

Back to top

basicline.gif (169 bytes)

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