Class Variables

advertisement
Classes and Objects - Program Development ...........................................................................................................1
Objectives .................................................................................................................................................................1
Introduction...............................................................................................................................................................1
Problem I – Generating Sales Report ...................................................................................................................1
Instance variables .................................................................................................................................................3
Instance Methods .................................................................................................................................................3
Class Variables .....................................................................................................................................................3
Class Methods ......................................................................................................................................................4
Overloading........................................................................................................................................................ 10
The Object Reference, this .................................................................................................................................... 11
Constants ............................................................................................................................................................ 13
Rules Governing Constants ...................................................................................................................... 14
Problem II – Customer Billing ........................................................................................................................... 15
Pitfalls ..................................................................................................................................................................... 25
Summary ................................................................................................................................................................. 26
Programming Projects............................................................................................................................................. 27
Classes and Objects - Program Development
Objectives






To know what are instance variables and class variables.
To know when to use instance variables as oppose to when to use class variables.
To know what are instance methods and class methods.
To differentiate how to call instance methods as opposed to calling class methods.
To know about the object reference object this, and be able to use it.
To develop approach to problem solving using object oriented approach
Introduction
Software development can range from simple program requirements to complex requirements. Some outputs can
look very intricate, but the programming is relatively simple, and vise versa. In the following two examples, we will
demonstrate that relatively simple program can generate rather impressive report even at this early stage.
In our discussion you will come across some Java concepts that were not discussed earlier; and rightly so, because
we did not needed then. We will discuss two categories of variables – instance variables and class variables.
Similarly, we will discuss the counterpart methods to these variables – instance methods and class methods.
Problem I – Generating Sales Report
A local furniture store ABC Furnishing, Inc, wishes to computerize its daily sales. You are required to write
a Java application program to generate a summary report for each day’s sale.
2
The program accepts the name of the product; the quantity sold day; and the gross amount in sale. The
program should also generate the total number of products sold and the gross sale for all the products. The
Figure 1 shows the format of the report.
ABC Furnishing, Inc
Sales Report for Oct 13, 2007
Product
Quantity
Amount($)
----------------------------------------Chair
20
1075.0
Table
20
1155.0
Lamp
10
175.0
Sofa
40
2255.0
----------------------------------------Total pieces sold 90
Total day's sale $4660.00
------------- End of report -------------
Figure 1Format of report.
Solution
Name of entity
Let us call this entity Sales; other names are just as good.
Attributes
At first glance we will need the following variables:

The name of the product

The quantity of product sold each day

The amount in daily sales
Methods
The program will require accessor methods to return the value for each of the variable.
Constructor
Every set product sold will have a name, the amount of money it was sold for, and the quantity sold. Hence, every
object will reflect these three values.
At a second glance we realize that we also need variables to accumulate:

The sales per product, and
3

The number of each product
These two variables will accumulate the amounts each time that a product is sold; hence they are not passed as
parameters; instead they are declared within the class.
Before we proceed any further, let us carry out further analysis on the variables. The first three variables discussed
above will be assigned their respective values every time that a sale is made; i.e., every time an object is created. On
the other hand the latter two variables will be update regardless of which product is sold. This difference in idea
gives rise to the classification of variables – instance variables and class variables.
Instance variables
Variables that depend on the creation of objects are called instance variables. The variables in all of the examples
that we have studied so far are instance variables. In the current exercise, the variables for the name of products, the
quantity sold, and the amount of money collected, are all instance variables. They can only be assigned values if a
transaction is carried out.
Instance Methods
Just as how we have instance variables, we also have instance methods. Instance methods are designed to access
instance variables. In other words, an instance method cannot be invoked unless an instance of the class is created;
and, an instance variable cannot be accessed by an instance method unless an instance of the class has been created.
All of the methods that we have discussed so far are instance methods.
Class Variables
Variables that do not depend on any particular instance of a class are called class variables. Class variables require
class methods to access them. Another feature of class variables is that there is only one copy of these variables
during the execution of the program. You can see by now why we want to discuss class variables – one to
accumulate the total number products, regardless of the object; and the other to total the amount of sales, regardless
of the object. The format for declaring a class variable is as follows:
static data_type nameOfVariable;
When declaring class variables, you must preface the variable name with the keyword static. Some people refer to
these types of variables as static variables. In addition, at compilation time these variables are assigned default
values if no value is explicitly assigned to them.
4
In our current example let us call the class variable required to accumulate the products, total_quantity; and the
variable to accumulate the sales, total_sales. Further, let us look at the way that they will be declared in the program.
The total of all products will be declared as follows:
static int total_quantity;
and for the total sales
static double total_sales;
Class Methods
Class methods are designed to access class variables. This kind of method does not rely on the existence of objects
either. As such you use the class name to communicate with them directly. Class methods must also be prefaced
with the keyword static. The format of the method is as follows:
static data_type methodName(<parameter>)
{
}
Now let us put the pieces together. Figure 2 shows a depiction of the solution to the problem.
Name: Sales
Instance Variables:
product
daily_sale
daily_quantity
Class Variables
total_sale
total_quantity
Constructor
Sales(product, cost, quantity)
Instance Methods
getProduct()
getPieces()
getSale()
Class Methods
getTotalSale()
getTotalQuantity()
Figure 2 A depiction of the Sales report program.
5
Listing 1 shows the code for this class, Sales.
1. public class Sales
2. {
3.
// class variables
4.
private static double total_sale;
5.
private static int total_quantity;
6.
7.
// Instance variables
8.
private String product;
9.
private double daily_sale;
10.
private int daily_quantity;
11.
public Sales(String name, double cost, int amount)
12.
{
13.
product = name;
14.
daily_sale = cost;
15.
daily_quantity = amount;
16.
17.
18.
total_sale = total_sale + cost;
19.
total_quantity = total_quantity + amount;
20.
}
21.
22.
// class method
23.
public static int getTotalQuantity()
24.
{
25.
return total_quantity;
26.
}
27.
28.
// class method
29.
public static double getTotalSale()
30.
{
31.
return total_sale;
32.
}
33.
34.
// instance method
35.
public double getSale()
36.
{
37.
return daily_sale;
38.
}
39.
40.
// instance method
41.
public int getPieces()
42.
{
43.
return daily_quantity;
44.
}
45.
46.
// instance method
47.
public String getProduct()
48.
{
49.
return product;
50.
}
51. }
Listing 1Code for the class Sales
Listing 1 has one new feature worth noting - the statements with the double forward slash (//). This kind of
statement is called a single line comment statement. Comment statements serve only as documentation to the
6
programmer or anyone reading the program. Comment statements are not executable. Also, notice that the
declaration of the variables, the format of the constructor, and the format of the methods are the same as in the
previous examples. There are only accessor methods in this class, and no mutator method, since we were not
required to change any values in the instance variables. Lastly, Lines 18 and 19 show how addition is carried out.
The statement:
total_sale = total_sale + cost;
reads as follows:
Add the contents of the variable cost to the contents of the variable total_sale and store the result back in the
variable total_sale. The statement on Line 20 has similar meaning.
Now that we have finished with the Sales class, let us design a client class that will interact with the Sales class by
creating objects of the Sales class, and generating the report requested. In analyzing the output, we notice that the
problem requires a presentable report, having a heading, the current date, underlining, adequate spacing between
values, and the dollar ($) sign – as in - Total day's sale $4660.00
The Java programming language has hundreds of classes that a programmer can use for various things. For instance,
there is:

The class Date that generates the current date.

The class DateFormat which allows us to format the date according to the following formats:
(i)
SHORT
10/12/07
(ii) MEDIUM
Oct 28, 2004
(iii) LONG
October 12, 2007
(iv) FULL
Friday, October 12, 2007

The class NumberFormat which formats numbers in various currencies, including the $ symbol, and the
guaranteed two places of decimal for cents position.
In addition to these classes, there are special sets of characters that control how the output is positioned on the output
line. For instance, there is the tab feature, which is comprised the two characters \t – which place fourteen spaces
between any two items. Then there is the new line feature which is comprised of these two characters \n – which
places the cursor on the succeeding line of an output. This may seems a whole lot to learn, but the benefit is that we
learn these features once, and apply them whenever we want them. As far as programming goes, we will almost
always want them, so we learn them early.
Next we look at the design of the client class. Let us call this class TestSales. The activities of this class are as
follows:
7
(i)
(ii)
(iii)
(iv)
Display the report heading
Create Sale objects with data.
Display the required information line by line.
Display summary information.
Listing 2 shows the code for the client class, TestSales. Whenever you want to use some Java pre-defined classes,
you must inform the Java compiler about your intention. The way to do this is by using the import statement in your
program. The import statement must precede the class statement. Lines 1 thru 3 of Listing 2 show the import
statement for each class.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
import java.util.Date; // Used for creating a Date object
import java.text.DateFormat; // Used for specifying the format of the date
import java.text.NumberFormat; // Used for specifying the type of currency
class TestSales
{
public static void main(String[] arg)
{
// Set up the formatters
Date d = new Date();
DateFormat df = DateFormat.getDateInstance();
NumberFormat nf = NumberFormat.getCurrencyInstance();
// Print the heading
System.out.println("\tABC Furnishing, Inc");
System.out.println();
System.out.println("Sales Report for " + df.format(d));
System.out.println("\n");
System.out.println("Product \tQuantity\tAmount($)");
System.out.println("-----------------------------------------");
// Create Sales objects
Sales w1 = new Sales("Chair", 1075.00, 20);
Sales w2 = new Sales("Table", 1155.00, 20);
Sales w3 = new Sales("Lamp", 175.00, 10);
Sales w4 = new Sales("Sofa", 2255.00, 40);
// Invoke the display method to display each object's information
display(w1);
display(w2);
display(w3);
display(w4);
// Display summary
System.out.println("-----------------------------------------");
System.out.println("Total items sold " + Sales.getTotalQuantity());
System.out.println("Total sale " + nf.format(Sales.getTotalSale()));
System.out.println("------------- End of report -------------");
System.out.println("\n");
}
static void display(Sales w)
{
System.out.println(w.getProduct() + "\t\t" + w.getPieces() +"\t\t" + w.getSale());
}
}
Listing 2 The client class TestSales creates objects, calls methods and prints report with the date
8
Next, we look at how the formatters are set up. In order get the current date you must created an instance of the Date
class. See Line 10 in the code.
10. Date d = new Date();
As we have seen, the DateFormat class has four ways of expressing the date. For now let us use the default format MEDIUM. Line 11 shows us how to use the default date format.
11. DateFormat df = DateFormat.getDateInstance();
Lines 15 thru 20 show how to set up the report heading. In particular Line 15 shows how the tab \t feature is used
to create space from the left edge.
15. System.out.println("\tABC Furnishing, Inc");
Line 16 simply creates an extra line space, but Line 17 shows how the date object gets formatted. That is,
17.
System.out.println("Sales Report for " + df.format(d) );
Line 18 shows how the new line feature is used to create extra line space. Line 19 uses the tab again – twice.this
time. Finally, Line 20 simply sets up a set of dashes.
Applying these statements to our program greatly enhance the looks of the output, and of course satisfy the
requirement.
Continuing with the class TestSales, we have created four Sales objects as shown in Lines 23 thru 26. The actual
parameter represents the name of the product, the amount of money, followed by the quantity of that product sold.
23. Sales w1 = new Sales("Chair", 1075.00, 20);
24. Sales w2 = new Sales("Table", 1155.00, 20);
25. Sales w3 = new Sales("Lamp", 175.00, 10);
26. Sales w4 = new Sales("Sofa", 2255.00, 40);
The program requires that the information for each object is display line by line. One way to do this is to write print
statements for each object. For example,
Sales w1 = new Sales("Chair", 1075.00, 20);
System.out.println(w1.getProduct() + "\t\t" + w1.getPieces() +"\t\t" + w1.getSale());
9
Sales w2 = new Sales("Table", 1155.00, 20);
System.out.println(w2.getProduct() + "\t\t" + w2.getPieces() +"\t\t" + w2.getSale());
But as you see with these four lines of codes, the second and fourth lines are the same pattern. Can you imagine
writing say five or ten lines of code for each object? There would be many repetitions. In programming, we
generally try and avoid repetition of codes. To solve this problem, we write methods that would contain the codes
common to objects. We will apply this concept in this exercise. Let us write a method called display. The reference
variables, w1, w2, w3, w4 are the actual parameter used to communicate with the display method, as shown in Lines
42 thru 46. The formal parameter w of method display is used to communicate with the three instance methods in
class Sales. The methods return the value in the respective instance variable. See Line 44 below.
42. static void display(Sales w)
43. {
44.
System.out.println(w.getProduct() + "\t\t" + w.getPieces() +"\t\t" + w.getSale());
45. }
Notice also that we have used the tab feature to put space between each value.
Finally, Lines 36 and 37 show how the class variables are accessed via the class methods getTotalQuantity())
and getTotalSale(). In addition, no reference variable is associated with these methods. Instead, the class name is
used to access these methods. This usage works because the methods are class methods. Class methods do not
require that an object exists in order to call them.
36. System.out.println("Total items sold " + Sales.getTotalQuantity());
37. System.out.println("Total sale " + nf.format(Sales.getTotalSale()));
Figure 3 shows the output generated from this program as required.
Figure 3 The output from the Sale program
10
Overloading
In the Object Oriented paradigm the concept of polymorphism is central to programming. One of the attributes of
a polymorphic system is that it has the ability to exhibit different behavior under different conditions. For example,
when you use a calculator to multiply two integers, or to multiply two floating-point values, or a combination of
both, the calculator is exhibiting polymorphic behavior, because the calculator is able to perform similar operations
on different data types.
In Object Oriented Programming constructors as well as methods can be defined in such way so that the object
behaves polymorphic. Parameter is what defines overloading. Method overloading requires at least two methods
with the same name. However, the parameters must be unique. The same conditions must exist when overloading
constructors.
If we were to design a class for the calculator mentioned above, we would design it with different constructors for
each combination of data. Listing 3 illustrates the concept of constructor overloading and method overloading.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
class Calculator
{
Calculator(int x, int y)
{
}
Calculator(int x, double y)
{
}
Calculator(double x, double y)
{
}
void add(double x)
{
}
void add(int x)
{
}
}
Listing 3 Method overloading and constructor overloading
The class has three constructors and two methods with the same name. The parameter lists for the constructors are
different in each case. Similarly, the parameters for the method add.
11
The Object Reference, this
When an object is created, the compiler generates an implicit reference variable to this object, called this. It can be
used refer to variables, methods, and constructors.
For instance, a parameter and a member variable may have the same name. To differentiate between them, you use
the this reference variable to refer to the member variable of this object. The format for implementing this concept
is as follows:
this.identifier = identifier;
Where identifier on the left is the member variable, and identifier on the right is the parameter variable. Listing 4
demonstrates its usage.
1.
2.
3.
4.
5.
6.
7.
8.
9.
public Circle
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
}
Listing 4 Reference variable, this, is associated with the member variable, radius.
The variable radius on the right is the parametric variable. This approach is used to avoid the programmer from
searching for new names for variables. When the variable, this, is used to qualify a method, it refers to a method in
the current class. The format for implementing this concept is as follows:
this.methodName( < parameter> );
If a class has more than one constructor, you may be able to use more than one of them to create a single object. This
approach avoids you from repeating existing codes. You can do so by using the implicit reference object, this.
Listing 5, Line 13 shows you how to use this to call to the single parameter constructor. So, instead of repeating
Lines 8 at Line 13 in the second constructor, we simply call the first constructor to carry out the initialization on its
behalf. This might look trivial, but imagine constructors with several statements, then you will appreciate this
concept. If this construct is used, then the call using this() must be the first executable statement in the constructor.
In addition, the parameters must be compatible.
12
1. public class Manufacturing
2. {
3.
private String name;
4.
private double price;
5.
6.
public Manufacturing(String name)
7.
{
8.
this.name = name;
9.
}
10.
11.
public Manufacturing(String s, double price)
12.
{
13.
this( s );
14.
this.price = price;
15.
}
16. }
Listing 5 illustrates the use of the this reference in the creation of the object Manufacturing
Exercises (2f)
1. How are overloaded methods distinguished from each other? Support your answer with three
method signatures.
2. Are the following pairs of methods properly overloaded? Explain.
a)
int method(int x, double y){… }
double method(int x, double y){… }
b)
int method(int x, double y) {… }
void method(double x, int y){… }
c)
void method(double x){ }
void method(int x, double y){… }
d)
int method(){… }
int method(int x, int y, double z){… }
3.
What will happen if you attempt to compile the following class?
4.
What will happen if you attempt to compile the following class?
13
1. public class Manufacturing
2. {
3.
private String name;
4.
private double price;
5.
6.
public Manufacturing( double p, String name)
7.
{
8.
this.name = name;
9.
price = p;
10.
}
11.
12.
public Manufacturing(String s, double p)
13.
{
14.
this(p, s);
15.
}
16. }
Constants
In Mathematics a fixed value is called a constant. The value for pi (π) is a typical example. In programming we use
similar concept. For instance, you might write a program that uses sales tax rate in its calculations. Tax rates rarely
change; hence, you can code sales tax as constants in your program.
In Java we use the modifier final to define constants. The format for defining a constant is as follows:
<modifier> final data_type nameOfConstant = value;
For instance, if the sales tax on goods is 5%, we could define a Java constant this way:
private final double SALES_TAX = 0.05;
Figure 4 explains the convention for naming constants in Java.
JLS recommends that the name of constants should be a descriptive sequence of one or
more words, acronyms, or abbreviations, all uppercase letters, with words separated by
underscore. Here are some identifiers representing constants: MAX_VALUE, PI, TAX
Figure 4 Convention for naming constants.
Let us revisit the class Circle to include the constant π. We will use the approximation of 3.14 to represent its value.
See Listing 6, Line 4.
14
1. public class Circle
2. {
3.
private double radius;
4.
private final double PI = 3.14;
5. }
Listing 6 Defining PI as a constant
Rules Governing Constants
Figure 5 shows the rules pertaining to constants
1.
A constant MUST be declared using the keyword final.
2.
A value of appropriate data type MUST be assigned to the
identifier representing the constant.
Figure 5 Rules pertaining to constants
Exercises (2g)
1. What is the meaning of the term constant as it pertains to programming?
2. How are constants defined in Java? Support your answer with at least two examples.
3. Given the following situations, identify the constants, if any.
(a)
The sales tax on consumer goods in Miami is 7%.
(b)
The room has a seating capacity of 35.
(c)
The capacity of the petrol tank is 20 gallons.
(d)
The speed of the car is 25 miles per hour.
4. Mortgage companies have different interest rate for potential home owners: first time home owners with
good credit get interest rate at 5¾%; first time home owners with poor credit rate get interest rate of 6¾%;
and investment property owners get interest rate of 8¼%.
15
Write a partial class definition to contain these different interest rates as constants. Choose identifier names
that match the situation.
5. The area of a regular octagon is given by the formula, A = 4.828a2, where a is the length of a side. Write a
partial class definition to represent the quantities 4.828 and a.
Problem II – Customer Billing
The ABC Cheap Lodging, Inc wants a computerized printout for each of its customers. Each input
consists of the room number, the number of nights, and the number of customers. A customer may
request additional night stay after the initial stay has expired. When registering, if customer a simply
request a room then it is assumed that it’s only one person staying one night. On the other hand the
customer may specify the length of stay. In this case it is assumed that there will be only one customer
for that many nights; or the customer may specify the length of stay and the number of guests. Figure 6.
shows the hotel’s room rate table.
Welcome to ABC Cheap Lodging, Inc
Rates Table
ROOM ………………$79.95 (per person)
TAX …………………6.5% (applies to room cost only)
TELEPHONE …….... $5.75 (Flat rate)
MEAL ……………... $ 12.95 (per person, per day)
TIP ………………….7.5% (cover all charges)
Figure 6 Hotel rate table
Figure 7 shows an example of what the output should be.
Figure 7 Example of the required output
16
Solution
Let us call this entity Hotel.
Attributes

The problem description specifies five constants as shown in the rate table. ROOM, TAX, TELEPHONE,
MEAL, and TIP. These constants aught to be private members, since it is not envisioned that any other
class will be interested in them.

Possible variables are. These variables aught to be private members also.
-
noOfNights
-
noOfGuest
-
amountDue
-
meal
-
tax
-
subtotal
-
total
-
tip
-
roomNumber
Constructors
There are three possible constructors
-
Single parameter (room number) – one customer staying one night.
-
Two parameters (room number and number of nights) – one customer staying as many nights.
-
Three parameters (room number, number of nights, and number of guests) – same as the former plus
the number of guests.
Methods
Possible actions that can be performed
-
Accessor methods require for each variable and constant.
-
A mutator method that carries out the necessary calculations.
Figure 8 is a depiction of the Hotel problem with fields, constructors, and methods.
17
Name: Hotel
Variables
noOfNights
noOfGuest
amountDue
meal
tax
subtotal
total
tip
roomNumber
Constructors
Hotel(roomNumber)
Hotel(roomNumber, nights)
Hotel(roomNumber, nights, guest)
Methods
getAmountDue()
getTaxDue()
getSubtotal()
subtotal()
getTip()
getMeal()
getRoomNumber()
getRoomRate()
getNumberOfNights()
getNumberOfGuests()
getPhoneCharges()
getTaxRate()
calculate()
add(nights):
Figure 8 showing the characteristics of the entity Hotel
As we have discussed earlier each variable is qualified by the type of data it expects to store. Against this
background the variables noOfNights and noOfGuest will be integer variables, since they suggest counting. The
variable roomNumber should be string, since it is not uncommon to se room number such as 12 – C. All the other
variables will be floating point..
The mutator method – calculate - has no formal parameter and will have no return values. It will simply acts on the
variables. The mutator method add on the other hand has one formal parameter but returns no value. Listing 7
shows the code for the class Hotel.
18
1.
public class Hotel
2.
{
3.
// Class constants
4.
private static final double ROOM_RATE
= 79.95;
5.
private static final double TAX_RATE
= 6.5;
6.
private static final double TELEPHONE
= 5.75;
7.
private static final double MEAL_COST
= 12.95;
8.
private static final double TIP_RATE
= 0.075;
9.
10.
// Instance variables
11.
private int noOfNights;
12.
private int noOfGuest;
13.
private double amountDue;
14.
private double meal;
15.
private double tax;
16.
private double subtotal;
17.
private double total;
18.
private double tip;
19.
private String roomNumber;
20.
21.
public Hotel(String room)
22.
{
23.
roomNumber = room;
24.
noOfGuest = 1;
25.
noOfNights = 1;
26.
}
27.
28.
public Hotel(String room, int nights)
29.
{
30.
this(room);
31.
noOfNights = nights;
32.
}
33.
34. public Hotel(String room, int nights, int guest)
34.
{
35.
this(room, nights);
36.
noOfGuest = guest;
37.
}
38.
39.
public void add(int nights)
40.
{
41.
noOfNights = noOfNights + nights;
42.
}
43.
44.
public void calculate()
45.
{
46.
amountDue = ROOM_RATE * noOfNights * noOfGuest;
47.
tax = amountDue * TAX_RATE/100;
48.
subtotal = amountDue + tax;
49.
meal = MEAL_COST * noOfNights;
50.
tip = TIP_RATE * (subtotal + meal + TELEPHONE);
51.
total = subtotal + TELEPHONE + meal + tip;
52.
}
19
53. public double getAmountDue() { ... }
54.
public double getTaxDue() { … }
55.
public double getSubtotal() { … }
56.
public double getTotal() { … }
57.
public double getTip(){ … }
58.
double getMeal() { …}
59.
public String getRoomNumber() { … }
60.
public double getRoomRate() { … }
61.
public int getNumberOfNights() { … }
62.
public int getNumberOfGuests() { … }
63.
public static double getPhoneCharges() { … }
64.
public static double getTaxRate() { … }
65. }
Listing 7The class definition Hotel
In analyzing the code, we see that Line 4 thru 8 defines the fixed values as constants. These constants are
independent of any particular objects; hence we make them class constants by using the keyword static. The
variables in Line 11 thru 19 are declared as instance variables since the value of each of these variables is
dependent on the individual customer. That is, the value for each of these variables is dependent on each
customer’s request.
There are three overloaded constructors as seen in Line 21 thru 38. We have introduced the keyword in this in
the previous section. Line 30 and 36 show how this keyword is used. Line 30 the statement this(room) invokes
the constructor with formal parameter of the string type. Similarly, the statement this(room, nights) invokes the
constructor with two parameters – the string parameter, and the int parameter. This is a common feature in Java.
This construct reduces the writing of codes, by re-using the codes of other constructors. The parametric
relationship between the statement this and the constructor that is being invoked must follow the same rules as
those of methods. In addition when it is used this way, it must be the first executable statement in the calling
constructor.
The mutator method add with formal parameter int nights, simply modifies the value of the variable noOfNights
by adding the parametric value to the variable noOfNights. The mutator method calculate, carries out arithmetic
calculations necessary for each customer’s costs. When calculations are involved, care must be taken in specifying
the order in which the arithmetic is done.
For instance:
1.
We could not have calculated the tax before calculating the amount due
2.
We could not have calculated the subtotal before knowing what the tax is
3.
The cost for the meal is independent of (1) and (2) and could have been calculated at any time, but
20
4.
The cost for meal must be calculated before the tip is calculated. The tip is a percentage of the overall
expenses – subtotal + meal + telephone charges. This calculation follows arithmetic principles – multiply
sum of expenses by the percentage (tip rate)
5.
The total must be the sum of all the expenses.
In this section we have introduced two new symbols for carrying out the calculations. They are the multiplication
symbol ( * ) used for the first time in Line 47 and the division symbol ( / ) used for the first time in Line 48.
Lines 55 thru 66 are incomplete accessor methods. When complete they simply return the value for each required
field. For instance the getAountDue method would be coded as follows:
double getAmountDue()
{
return amountDue;
}
The other methods follow similar form.
Listing 8 shows the code for the client class TestHotel.
21
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
import java.util.Date;
import java.text.DateFormat;
import java.text.NumberFormat;
class TestHotel
{
public static void main(String[] arg)
{
// Create customer objects, calculate amounts, display receipts
Hotel customer1 = new Hotel("12 - B");
customer1.calculate();
displayReceipt(customer1);
Hotel customer2 = new Hotel("12 - C", 2);
customer2.calculate();
displayReceipt(customer2);
}
static void displayReceipt(Hotel h)
{
// Set up and display heading and date for each receipt
System.out.println("\tThe ABC Cheap Lodging, Inc");
Date d = new Date();
DateFormat df = DateFormat.getDateInstance();
System.out.println("\tDate: \t" + df.format(d));
NumberFormat f = NumberFormat.getCurrencyInstance();
// Disply expenses line by line including subtotal
System.out.println("Room# \t\t" + h.getRoomNumber());
System.out.println("Room Rate: \t" + f.format(h.getRoomRate()));
System.out.println("Length of stay\t" + h.getNumberOfNights() + " nights");
System.out.println("No. of guests: \t" + h.getNumberOfGuests());
System.out.println("Room cost: \t" + f.format(h.getAmountDue()));
System.out.println("Tax : " + h.getTaxRate() + "%\t" + f.format(h.getTaxDue()));
System.out.println("\tSubtotal \t" + f.format(h.getSubtotal()));
System.out.println("Telephone \t" + f.format(h.getPhoneCharges()));
System.out.println("Meal charges \t" + f.format(h.getMeal()));
System.out.println("Tip \t\t" + f.format(h.getTip()));
//Display to total
System.out.println("\nTOTAL AMOUNT DUE\t" + f.format(h.getTotal()));
// Display thank you message
System.out.println("\nThanks for staying at The ABC Cheap Lodging, Inc" );
System.out.println("\tPlease come again !!!");
System.out.println("\n");
}
}
Listing 8 The class TestHotel
This client class TestHotel re-enforces much of the previously explained concepts. The method main simply
directs operations the following way:
22
1.
Creates guest (Hotel) objects – customer1 and customer2.
2.
Calculates their expenses by calling the calculate method in class Hotel, and
3.
Displays the receipts by calling the displayReceipt in its own class.
Once again it is necessary to write one method for the codes that are common to all the objects; hence the need for
the class displayReceipt. In the previous example the method display had only one statement, this time the method
displayReceipt has 19. The Date class and the DateFormat class have been used again. Much use has been made of
the tab feature, the new line feature, and the currency formatter. These are routine task, and in no time you will
master them.
Exercise 2(h)
1.
Differentiate between class method and instance method.
2.
Can class method access instance variables? If not, why not.
3.
Can instance method access class variables? If yes, explain why it is possible.
4.
How are instance methods called?
5.
How are class methods called?
6.
Is it possible to call an instance method without creating an instance of the class?
7.
Under what condition can a method be called without creating an instance of the class?
8.
Given the following variable declarations, identify those that are class variables from those that are instance
variables.
(a) private double money;
(b) public static double rate;
(c) private String word;
(d) private static int capacity = 35;
(e) public int noOfChildren;
9.
At department stores, each customer pays for the goods that he/she selects. The customer’s bill shows the
total and the number of items purchased. The cashier on the other hand keeps track of the total for the day’s
sale.
23
(a) From the given situation, identify at least two instance variables, and at least two class
variables.
(b) Write the class definition for this situation.
10. What will happen if you attempt to compile the following Java code?
class A
{
static int count;
int weight;
A(int d)
{
weight = d;
}
static int getWeight()
{
return weight;
}
}
11. What will happen if you attempt to compile the following Java code?
class A
{
static int count;
int weight;
A(int d)
{
count = d;
}
int getCount()
{
return count;
}
}
12. What will be printed from the class chain when the class TestChain is executed?
public class Chain
{
public Chain(double x)
{
this("Hello");
}
public Chain(String str)
{
this();
24
System.out.println(str);
}
public Chain()
{
this(200);
System.out.println("years");
}
public Chain(int x)
{
System.out.println(x);
}
}
public class TestChain
{
public static void main(String arg[])
{
Chain ch = new Chain(100.0);
}
}
13. Refer to Exercise 2(e) Question 9, define a test class called TestTrading. Create two objects t1 and t2.

t1 is a leather sofa, cost $3,599.90 and sold for $4,599.90.

t2 is a bed set, cost $6,299.90 and sold for $8,500.95.
In your design, consider the following:

Write a static method that incorporates common codes.

Use the classes Date and DateFormat to generate the current date.

Use the class NumberFormat to present the output in monetary form.
Your program must generate an output similar to the one below.
25
14. Refer to Exercise 2(e) Question 10, define a test class called TestSimpleInterest. Find the simple
interest and the total amount on:
(i)
$2,500 for 6 years at 5% interest
(ii)
$75,900 for 10 years at 7.25% interest.
Pitfalls

Class name and File name different.
It is a common mistake to name the Java file differently from the class name. For instance, if the class is
called Book.java, it is a common mistake to call the file book.java; and vise versa.

Creating object without the operator new.
A mistake infrequently make is attempting to create objects without using the operator new. For instance,
writing the code this way:
Book b1 = Book(“("OOP using Java", "000-000-00001", 895, 85.95);

Changing Object’s Value
Once you have created an object, you cannot use that constructor to change any of the original values that
were assigned. For example,
26
Book b1 = new Book("OOP using Java", "000-000-00001", 895, 85.95);
Then
b1 = new Book("OOP using Java", "000-000-00001", 895, 105.95);
This usage will not replace the price of the book, what this does, is to create a different object. In order to
change the value of any field you will need methods.

Change Value of Constant
Another misunderstanding is to believe that you can pass values via methods to change the constant’s
value. During the execution of the program it cannot be done. You will simply have to edit the program.

Constructor with return Type
Another common but unconscious mistake, is to attach the type void to constructor. Constructors do not
have return types – not even void.

Mutator method with return type
This happens, rarely, but needs pointing out. Mutator methods do not have return type.

Mismatch Parametric Types
One common mistake that almost everyone makes is a mix-up between the actual parameter and the formal
parameter. Sometime its is negligence, sometimes lack of knowledge.
Summary
In this chapter we covered the fundamental concepts of the type class and objects.
1.
The fundamental concepts of Object Oriented Programming (OOP).
2.
The concept of entity and how it helps in defining classes.
3.
What an object is as it pertains to the class.
4.
How to define class in terms of its name, variables, and methods.
5.
Modifiers - especially private, public, and static modifiers.
27
6.
What identifiers are, and the conventions that are adopted in naming them.
7.
The modifier final is used to define a constant.
8.
What constructors are their purpose and how to define them.
9.
Java defines two types of variables: instance variables and class variables. Instance variables cannot be
accessed unless an object is created. Class variables can be accessed by class variables; in this case you do not
have to create instance of the class.
10. Java defines three types of methods: instance method, class method, and constructor.
11. Instance methods can only be called if an object is created.
12. Class methods can be called without creating instance of the class. This is permissible if no instance variable is
involved.
13. Instance methods and class methods must have a return type. The modifier void must be used if the method is
expected to return no value.
14. Constructors are a special member method. They are used to initialize objects, by allocating sufficient memory
for the member variables of the class. Constructors do not carry return types, not even the type void.
Constructors have the same name as the name of the class.
15. Instance methods versus class methods.
16. Accessor methods versus mutator methods.
17. How other classes communicate with class methods versus instance methods.
18. How to display information using the print() and println() methods.
19. Overloading is central to Object Oriented Programming. Both the constructor and method can be overloaded.
20. Comment statements – single line comment versus multiple lines statements.
21. Use Java pre-defined classes – Date and DateFormat, to extract and format current date.
22. Use Java pre-defined classes – NumberFormat, to format currency.
Programming Projects
1.
Write a class called Bank. A bank consists of the customer account number and an initial amount when the
account is opened. The customer may deposit money any number of times during the day; similarly, the
28
customer may withdraw money any number of times during the day. Each time a transaction is carried out a
printed report of it is made. See typical output below.
Use the following program to test your class.
class TestBank
{
public static void main(String[] arg)
{
Bank b = new Bank(100, "098-055-9325");
System.out.println("Account: " + b.getAccountNumber() + "\tOpening balance $" + b.getBalance());
b.deposit(50);
System.out.println("Deposit $" + b.getTransaction() + "\t\tNew balance $" + b.getBalance());
b.withdraw(25);
System.out.println("Withdraw $" + b.getTransaction() + "\t\tNew balance $" + b.getBalance());
b.deposit(150);
System.out.println("Deposit $" + b.getTransaction() + "\t\tNew balance $" + b.getBalance());
}
}
2.
Implement a class called Employee. An employee has a name and gets a salary. Every pay period the gets an
amount in bonus. Include a constructor that accepts the name and salary of an employee. Provide a mutator
method that accepts the bonus amount and add it to the salary. Provide necessary accessor methods to return
each field value
Implement a test class called TestEmployee to produce output similar to the one below.
29
3.
Write a Java program that can be used to find the area and perimeter of a rectangle. In designing your program,
given consideration to the following:
(a) Write a class called Measurement to calculate and return the area and perimeter of a rectangle. In your
design consider the following:

Member variables – length, width, area, perimeter.

Constructor that accepts the length and width of each rectangle.

Instance mutator method calculates that computes the area and the perimeter of a rectangle.

Instance mutator methods, one to change length, and the other to change the width.

Accessor methods that returns the value of each attributes.
(b) Write a test class called TestMeasurement to test your class Measurement. Create two rectangle objects with
initial sizes 10 ft by 5 feet; and 25 feet by 30 feet. Print the measures for both objects. Next, increase the length
of the first by adding 2 units to the length; and decrease the second by subtracting 5 units from the width. Now
print the measures for both objects.
4.
Write a Java program that can be use to calculate the weekly salary for hourly paid employees. The program
must:

Create three employee objects

Write a mutator method called calculate that calculates the salary per employee and accumulate total
amount of salary the company pays out weekly.

Print the salary for each employee

Prints the total amount of money paid out on a weekly basis.

Your output must be similar to the following:
30
In designing your program consider the following:
(a) Write a class called WeeklyPayroll to include, but not limited to:

Instance variables for number of hours worked, and hourly rate of pay.

Class variable for accumulating the weekly payroll.

A mutator instance method that calculates an employee salary, and accumulates the weekly payroll.

Accessor methods for the respective fields.

Constructor that accepts employee number, number of hours worked, and the hourly rate per employee.
(b) Design a test class called TestPayroll that implements the WeeklyPayroll class.
5.
Write a program to calculate the property tax. Property tax is calculated on 92% of the assessed value of the
property. For example, if the assessed value is $100,000.00, the property tax is on $92,000.00. Assume that the
property tax rate is $1.05 for each $100.00 of the assessed value. Your program should produce an output
similar to the following.
The following test class generates the following output. Write the class PropertyTax.
import java.text.NumberFormat;
class TestPropertytax
{
public static void main(String[] arg)
{
NumberFormat nf = NumberFormat.getCurrencyInstance();
PropertyTax p1 = new PropertyTax(100000, 1.05);
31
p1.calculate();
print(p1, nf);
System.out.println("----------------------------------");
PropertyTax p2 = new PropertyTax(150000, 1.05);
p2.calculate();
print(p2, nf);
System.out.println("----------------------------------");
System.out.println("Total tax revenue " + nf.format(PropertyTax.totalTax()));
System.out.println("--------- End of report ----------");
}
static void print(PropertyTax p, NumberFormat nf)
{
System.out.println("Assessed value " + nf.format(p.getAssessedValue()));
System.out.println("Taxable amount " + nf.format(p.getTaxAbleAmount()));
System.out.println("Tax rate for each $100.00 is " + nf.format(p.getTaxRate()));
System.out.println("Property tax is " + nf.format(p.getTax()));
}
}
Download