Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web...

41
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.

Transcript of Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web...

Page 1: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

Classes and Objects - Program Development............................................................................................................1

Objectives...................................................................................................................................................................1

Introduction................................................................................................................................................................1Problem I – Generating Sales Report....................................................................................................................1Instance variables..................................................................................................................................................3Instance Methods...................................................................................................................................................3Class Variables......................................................................................................................................................3Class Methods.......................................................................................................................................................4Overloading.........................................................................................................................................................10

The Object Reference, this.....................................................................................................................................11Constants.............................................................................................................................................................13

Rules Governing Constants.......................................................................................................................14Problem 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

IntroductionSoftware 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 ReportA 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.

Page 2: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.0Table 20 1155.0Lamp 10 175.0Sofa 40 2255.0-----------------------------------------Total pieces sold 90Total 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

The number of each product

2

Page 3: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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 variablesVariables 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 MethodsJust 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 VariablesVariables 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.

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.

3

Page 4: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

The total of all products will be declared as follows:

static int total_quantity;

and for the total sales

static double total_sales;

Class MethodsClass 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.

Figure 2 A depiction of the Sales report program.

Listing 1 shows the code for this class, Sales.

4

Name: Sales

Instance Variables:productdaily_saledaily_quantity

Class Variablestotal_saletotal_quantity

Constructor Sales(product, cost, quantity)

Instance MethodsgetProduct()getPieces()getSale()

Class MethodsgetTotalSale() getTotalQuantity()

1. public class Sales2. {3. // class variables4. private static double total_sale;5. private static int total_quantity;6.7. // Instance variables8. 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 method23. public static int getTotalQuantity()24. {25. return total_quantity;26. }27.28. // class method29. public static double getTotalSale()30. {31. return total_sale;32. }33.34. // instance method35. public double getSale()36. {37. return daily_sale;38. }39.40. // instance method41. public int getPieces()42. {43. return daily_quantity;44. }45.46. // instance method47. public String getProduct()48. {49. return product;50. }51. }

Page 5: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

Listing 1Code for the class SalesListing 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

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

5

Page 6: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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:

(i) Display the report heading(ii) Create Sale objects with data.

6

Page 7: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

(iii) Display the required information line by line.(iv) 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.

Listing 2 The client class TestSales creates objects, calls methods and prints report with the date

7

1. import java.util.Date; // Used for creating a Date object2. import java.text.DateFormat; // Used for specifying the format of the date3. import java.text.NumberFormat; // Used for specifying the type of currency4.5. class TestSales6. {7. public static void main(String[] arg)8. {9. // Set up the formatters10. Date d = new Date();11. DateFormat df = DateFormat.getDateInstance();12. NumberFormat nf = NumberFormat.getCurrencyInstance();13.14. // Print the heading15. System.out.println("\tABC Furnishing, Inc");16. System.out.println();17. System.out.println("Sales Report for " + df.format(d));18. System.out.println("\n");19. System.out.println("Product \tQuantity\tAmount($)");20. System.out.println("-----------------------------------------");21.22. // Create Sales objects23. 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); 27.28. // Invoke the display method to display each object's information29. display(w1);30. display(w2);31. display(w3);32. display(w4);33.34. // Display summary 35. System.out.println("-----------------------------------------");36. System.out.println("Total items sold " + Sales.getTotalQuantity());37. System.out.println("Total sale " + nf.format(Sales.getTotalSale()));38. System.out.println("------------- End of report -------------");39. System.out.println("\n");40. }41.42. static void display(Sales w)43. {44. System.out.println(w.getProduct() + "\t\t" + w.getPieces() +"\t\t" + w.getSale());45. }46. }

Page 8: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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());Sales w2 = new Sales("Table", 1155.00, 20);

8

Page 9: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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

9

Page 10: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

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.

10

1. class Calculator2. {3. Calculator(int x, int y)4. {5.6. }7. Calculator(int x, double y)8. {9.10. }11. Calculator(double x, double y)12. {13.14. }15. void add(double x)16. {17.18. }19. void add(int x)20. {21.22. }23. }

Page 11: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

The Object Reference, thisWhen 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.

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.

11

1. public Circle 2. {3. private double radius;4.5. public Circle(double radius)6. {7. this.radius = radius;8. }9. }

Page 12: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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?

12

1. public class Manufacturing2. {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. }

Page 13: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

1. public class Manufacturing2. {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. }

ConstantsIn 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.

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.

13

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

1. public class Circle2. {3. private double radius;4.private final double PI = 3.14;5. }

Page 14: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

Listing 6 Defining PI as a constant

Rules Governing Constants

Figure 5 shows the rules pertaining to constants

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¼%.

14

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.

Page 15: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

Figure 6 Hotel rate table

Figure 7 shows an example of what the output should be.

Figure 7 Example of the required output

Solution

15

Welcome to ABC Cheap Lodging, Inc

Rates TableROOM ………………$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)

Page 16: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

16

Page 17: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

17

Name: Hotel

VariablesnoOfNightsnoOfGuestamountDuemealtaxsubtotaltotaltiproomNumber

ConstructorsHotel(roomNumber)Hotel(roomNumber, nights)Hotel(roomNumber, nights, guest)

MethodsgetAmountDue()getTaxDue()getSubtotal()subtotal()getTip()getMeal()getRoomNumber()getRoomRate()getNumberOfNights()getNumberOfGuests()getPhoneCharges()getTaxRate()calculate()add(nights):

Page 18: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

18

1. public class Hotel2. {3. // Class constants4. 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 variables11. 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. }

Page 19: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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

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. }

Page 20: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

20

Page 21: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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:

21

1. import java.util.Date;2. import java.text.DateFormat;3. import java.text.NumberFormat;4.5. class TestHotel6. {7. public static void main(String[] arg)8. {9. // Create customer objects, calculate amounts, display receipts10. Hotel customer1 = new Hotel("12 - B");11. customer1.calculate();12. displayReceipt(customer1);13.14. Hotel customer2 = new Hotel("12 - C", 2);15. customer2.calculate();16. displayReceipt(customer2);17. }18.19. static void displayReceipt(Hotel h)20. {21. // Set up and display heading and date for each receipt22. System.out.println("\tThe ABC Cheap Lodging, Inc");23. Date d = new Date();24. DateFormat df = DateFormat.getDateInstance();25. System.out.println("\tDate: \t" + df.format(d));26. NumberFormat f = NumberFormat.getCurrencyInstance();27.28. // Disply expenses line by line including subtotal29. System.out.println("Room# \t\t" + h.getRoomNumber());30. System.out.println("Room Rate: \t" + f.format(h.getRoomRate()));31. System.out.println("Length of stay\t" + h.getNumberOfNights() + " nights");32. System.out.println("No. of guests: \t" + h.getNumberOfGuests());33. System.out.println("Room cost: \t" + f.format(h.getAmountDue()));34. System.out.println("Tax : " + h.getTaxRate() + "%\t" + f.format(h.getTaxDue()));35. System.out.println("\tSubtotal \t" + f.format(h.getSubtotal()));36. System.out.println("Telephone \t" + f.format(h.getPhoneCharges()));37. System.out.println("Meal charges \t" + f.format(h.getMeal()));38. System.out.println("Tip \t\t" + f.format(h.getTip()));39.40. //Display to total41. System.out.println("\nTOTAL AMOUNT DUE\t" + f.format(h.getTotal()));42.43. // Display thank you message44. System.out.println("\nThanks for staying at The ABC Cheap Lodging, Inc" );45. System.out.println("\tPlease come again !!!");46. System.out.println("\n");47. }48. }

Page 22: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

(a) From the given situation, identify at least two instance variables, and at least two class

variables.

22

Page 23: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

(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();System.out.println(str);

}public Chain(){

23

Page 24: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

24

Page 25: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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,

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

25

Page 26: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

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.

26

Page 27: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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

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.

27

Page 28: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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.

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:

28

Page 29: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

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:

In designing your program consider the following:

29

Page 30: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

(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);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()));

}}

30

Page 31: Preface - users.cis.fiu.eduusers.cis.fiu.edu/~smithjo/classnotes_2xxxx/lesson_03.doc  · Web viewThe Object Reference, this. When an object is created, the compiler generates an

31