Chapter 1



Lessons 2 – 3

Objects and Classes

Part I

Objectives

• To understand the concepts of Objects and Classes as they pertain to the subject Object Oriented Programming.

• To understand the relationship between Objects and Classes.

• To learn how to define a class in terms of its name, variables, methods, and constructors.

• To differentiate between class variables and instance variables.

• Be able to define constants.

• To understand the difference between class methods and instance methods.

• To learn how to create objects of a class.

• To learn how to call instance methods.

• To learn how to call class methods.

• To understand what access attributes are and how to use them in a class.

• To be acquainted with the concept of Java Garbage collection mechanism, and what role its plays in a program.

Introduction

This set of lessons lays the foundation to understanding Object Oriented Programming (OOP). The concept of Objects and Classes form the cornerstone to the subject. As a result, we begin by establishing the fundamental concepts of Objects and Classes, and how they relate to programming. The next key element to understand is what constitutes a class. This is followed by a discussion of each component of a class –variables, methods, and constructors. Next it discusses what objects are and how to create them. This is followed by a discussion on the finer details of classes. This includes further discussion on modifiers, method overloading, and constructor overloading, and default constructor. It also looks at other ways of calling methods, and how objects communicate. The session concludes with a discussion on the topic Garbage Collection.

Fundamental Concepts

The Object Oriented Programming paradigm is based primarily on the concept of objects. In terms of natural language, the Webster’s New World Dictionary definition of an object is:

1. A thing that can be seen or touched; material thing that occupies space.

2. A person or thing to which action, thought or feeling is directed.

3. A noun or other substantive that directly or indirectly receives the action of a verb.

From this definition one concludes that an Object is an entity characterized by its name and the things that it encapsulates. The things that are encapsulated by an object are the components that make up the entity, the things the entity can do, or the things that can be done to it. Using natural language, we refer to the components that made up the entity, nouns and the actions that the entity can carry out, verbs.

If we look around us, everything that we see or can think of are objects, because each entity has a name, components that characterize it, and actions that tell of its behavior. To help us understand the concept of objects, consider the following three examples:

Example 2.1

A person who conducts a class is often referred to as a professor. List some nouns and some verbs that best fit the entity, professor.

Name of Entity Elements (Nouns) Action (Verbs)

Professor Hands Walk

Feet See

Eyes Eat

Intellect Teach

Sleep

These are only a few of the elements that make up this entity. I am sure that you can find some more.

Example 2.2

Given the radius of a circle, find its circumference and its area. Describe the entity by naming it areaAndCircumference, and state at least two nouns that are relevant to it. Also, list at least two possible verbs that would be relevant to this entity.

Name of entity Elements (Nouns) Action (Verbs)

areaAndCircumference radius findCircumference

pi findArea

In this situation the entity areaAndCircumference requires at minimal the value for the radius and the value for pi in order to find its circumference and its area. I named the actions (verbs) findArea and findCircumference to match the situation.

Notice that we were not asked to solve the problem, but rather to identify the characteristics of the given situation as the entity.

Sometimes a given situation could describe several entities. It is the responsibility of the reader to determine what the entities are. For instance, let us consider Example 2.3.

Example 2.3

A company has four categories of employees: namely, manager, who gets a fixed salary; hourly worker, whose salary is calculated based on the number of hours worked; piece worker, whose salary is calculated by the number of products completed; and commission worker, who gets a fixed amount and also a percentage of the sales. Every two weeks the company’s accountant gets each employee’s worksheet and prepares each employee’s paycheck.

Decompose this situation into as many entities as you can, and list the possible nouns and possible verbs for each entity.

At first one may wonder where to start, but with closer analysis you will recognize that each category of worker could be regarded as individual entities, since the way that their salary is calculated is different. Also, worksheet that contains the data for the employee is a separate entity, because it holds information for each employee. Against this background, we identify a minimum of five entities. They are described below.

Entities Nouns Verbs

employeeRecord Name setName

Amount setAmount

CommissionRate setCommissionRate

HourlyRate setHourlyRate

PieceRate setPieceRate

Manager employeeRecord getAmount

setSalary

hourlyWorker employeeRecord getHoursWorked

getHourlyRate

calculateSalary

pieceworker employeeRecord getNumberOfCompletePieces

getPieceRate

calculateSalary

Entities Nouns Verbs

commissionWorker employeeRecord getFixedAmount

getCommissionRate

getSalesAmount

calculateSalary

This might look overwhelming at first, but remember – we are not asked to write a program; all that we are asked to do is to identify possible entities, and list the characteristics of each entity identified. For instance, the accountant collects the information for each worker and uses that information to make up a record for the employee. The accountant uses that record, and depending on which category the worker is, the accountant calculates the salary based on the rule for that category of worker. This is everyday occurrence.

It might take you a while to do something like Example 2.3, but you should think this way- identifying entities. These are but a few examples. Once we have identified entities and their characteristics, then the rest (writing the code) becomes clear.

Defining Objects

In natural language you can specify a particular instance of an entity. For instance, motorcar is an entity, but the model Ford Mustang is an instance of motorcar; similarly, Toyota Corolla is another instance of motorcar. These are separate instances; if we change the color of the Mustang, this change has no effect on the color of the Corolla. In addition, you cannot drive the generic description motorcar, but you can drive a particular instance of motorcar.

In Example 2.1 an instance of the entity Professor is: Professor James Nooks.

In Example 2.2 an instance of the entity areaAndCircumference is a circle whose radius is 10 units.

Similarly, in Example 2.3 two instances of this situation are:

1. John Miller who is a manager and has a salary of $20,000 and

2. Hillary Martin who works 60 hours at a rate of $15 per hour.

Notice that in example 2.3, case 1, the instance John Miller belongs to the entity, manager; but the second instance Hillary Martin belongs to the entity hourlyWorker.

The following section discusses the concept of what a class is, and how it relates to the concept of an entity.

Exercises 2(a)

The following exercises are designed for you to recognize entities and instances of

entities. That is, you are not being asked to solve for a numeric value, just to

identify entities and objects of each entity.

1. Explain in your own words the meaning of the term entity.

2. Look around you and write down four entities.

3. Explain in your own words the meaning of the term object.

4. State two objects from each of the entities that you named in (2).

5. Suppose a company bought an item for certain amount of money and sells it. Calculate the revenue generated. (Do not be concerned about solving for a value.)

a) Recognize that this situation describes an entity, and give it a name.

b) List possible nouns for this entity.

c) List possible verbs for this entity.

d) List two instances of this entity. That is, give two examples of such a transaction - cost of item and amount that it is sold for.

6. A certain amount of money has been invested in your savings account for a certain number of years at simple interest.

a) Recognize that this situation describes an entity and give it a name.

b) List possible nouns for this entity.

c) List possible verbs for this entity.

d) List two instances of this entity. That is, give two examples of the amount of money, the number of years, and possible interest rate.

Defining Classes

Object Oriented Programming languages use the concept of class or some such term to describe entities. In other words, in natural language the term entity is used, but in computer programming jargon the term class is used. This means that a class must have a name, like the entity; it may have nouns; it may have verbs; or have both nouns and verbs. In programming the term variable or identifier is used instead of the word noun; and the term method is used instead of the term verb. Furthermore, the description of the class is more formally laid out than how entity is described in natural language. In Java, a class may have any or all of the following three elements encapsulated under the class name:

• Member Variables

• Member Methods

• Constructors (Special methods)

Figure 2.1 shows the format for describing a class in Java. The pair of angled brackets indicates that the items that they enclosed are optional.

Figure 2.1 The general format for describing a class in Java.

As you read, make note of the following:

a) The word class is used to denote that an entity is being formed

b) The class is given a name. The name can be any name you choose. The only restriction is that you are not permitted to use Java reserved words. See Appendix A for the set of Java reserved words.

c) The member variables, the member methods, and the constructors. Each of these components will be discussed.

d) Constructors are special method. We will discuss constructors and the role they play in a class later.

e) Modifiers are words or keywords that are used to qualify elements of a class. Some of the modifiers in Java are: private, protected, public, static, and final. In some cases modifiers are optional. Modifiers will be discussed.

In Object Oriented Programming you cannot use the class definition directly. You will have to specify a particular instance of the class or in some special cases use the class name along with a method to access elements in the class. Specifying an instance of the class means that you have to acquire enough memory to store the values of the variables in the class. The instance of the class is referred to as an object of the class, and the variable that refers to it is called the reference variable or reference object. Each instance of a class is a different object; hence each requires different chunks of memory for its instance variables. This is analogous to the motorcar example above. See Figure 2.2. We will formally specify how to create objects later.

Reference

Objects

Figure 2.2 Three objects occupying memory

Variables

A variable is a named piece of memory that is used to store data. You use variables in a program to store data. One way to think of variables is a letterbox that can hold one value. On the face of the letterbox is the address, and within the compartment is the area to store one piece of data. If there is a value already in the letterbox and we try to put another value in, we lose the first value.

When you are declaring variables you must specify the kind of data that will be stored in them, because each type of data requires different amount memory. Data types will be discussed in future lessons.

Variable Names

The name you choose for a variable is sometimes referred to as identifier. The two words are used interchangeably. An identifier can be composed of any number of characters. It must start with a letter, an underscore, or a dollar sign. The rest of the identifier can include any character except arithmetic symbols, special characters such as punctuation symbols, or embedded space.

The following are valid identifiers in Java:

• PayRate

• interesT

• $commission

• mine2

• _good_Identifier

The following are invalid identifiers in Java:

Identifiers Reason

• Employee Salary - has embedded blank

• 2Employees - begins with a digit

• myEmployee? - has punctuation symbol

• sum-difference - has arithmetic operator.

Java is case sensitive. Uppercase letters and lower case letters are considered to be different. Hence the following pairs of identifiers are not the same.

• computerscience computerScience.

• Payrate payRate

• generaLaccOUnt generalAccount

Although the identifiers in each pair have the same sequence of characters, some of the cases are different, which makes the identifiers different.

There are two kinds of variables in Java; they are instance variables and class variables. We will study these types in the next two sections, and we will use them throughout programming in Java.

Exercises (2b)

1. Explain in your own words how a class is defined in Java. You must account for its name and its components.

2. Why is it not always possible to execute a class after it has been defined?

3. With respect to Object Oriented Programming, what does the term object means?

4. What are variables?

5. Explain the proper way of naming variables.

6. Explain what would make a variable invalid.

7. In Exercises (2a) question 5, list at least two variables in that entity. Make sure that you obey the rules for naming variables.

8. In Exercises (2a) question 6, list at least three variables in that entity. Make sure that you obey the rules for naming variables.

Instance Variables

Instance variables, sometimes referred to as member variables, are variables that are declared inside the class, but not inside a method, or a constructor. Instance variables are accessible by constructors and instance methods, but not by class methods. Constructor, instance method, and class method will be discussed later. Instance variables are accessible only when objects are created. This means that:

• Each object gets a copy of each instance variable that is declared in the class.

• The values of the variables in one object cannot affect the values of the variables in other objects. That is, if an object modifies the value of its copy of an instance variable, then the new value will not affect any other object of the class. As was mentioned earlier the analogy is, if we denote motorcar to be a class, then a Ford Mustang is just one instance of motorcar; similarly, Toyota Corolla is another instance of motorcar. If we change the color of the Mustang, this change will not affect the color of the Corolla, because the instances are separate objects.

• Instance variables are dead once no more reference can be made to that particular object.

The format for declaring an instance variable is as follows:

data_type variableName;

Where modifier is one of the following keywords:private, protected, or public.

As mentioned earlier, data types will be discussed, but for now we will use three of them in our discussion. These are:

String – This data type represents a sequence of characters. For example the following set of characters “Today is Tuesday”, within the quotation denotes is a string.

int – This is a numeric data type. It is used to represent whole numbers; i.e., numbers without decimal. For instance the value 150 is an integer.

double – This data type is also a numeric type but it is used to represent one kind of floating point numbers (decimals). For example the value 150.5 is a floating-point (decimal) value.

Going back to Figure 2.2 it should be clear that each bubble represents a different object. This means that value of the radius for each object may be different, so the variable radius is declared instance variable. See Listing 2.1 how instance variables are declared inside the class.

1. class areaAndCircumference

2. {

3. private double radius;

4. }

Listing 2.1 Declaring Instance variables in class areaAndCircumference.

In Listing 2.1, Line 1 declares a class whose name is areaAndCircumference. The pair of braces shown in Lines 2 and 4 encloses the class definition. The only item that makes up this class so far is the instance variable, radius, shown on Line 3. The modifier private means that this variable is accessible only by this class. If we create objects with this class, each object will have a separate memory space for its instance variable, radius. See Figure 2.3 for a depiction of the concept.

Reference

Objects

Figure 2.3 Three Objects Created From the class areaAndCircumference

Note that if a value is stored in the variable radius of say Object A, this value will not affect the values stored in Object B or Object C, because each object occupies different memory space.

Class Variables

Class variables like instance variables are declared as members of the class. However, unlike instance variables, class variables are shared by all instances of the class. This means that no matter how many objects are created, only one copy of each class variable exists. If one of the objects modifies the value of a class variable, then the new value will be reflected in all of the other objects of the class. When Java encounters a class containing class variables for the first time, the compiler allocates memory for each class variable right away. Class variables can be accessed without any object being created. Later we will see exactly how this is done. Class variables must be declared using the modifier static preceding the data type and variable name. The format for declaring a class variable is as follows:

static data_type variableName;

Or

static data_type variableName = value;

In the first case you simply declare the variable; in the second case you do not only declare it, but you also assign a value to it.

Before we continue, let us see how this discussion fits in context with Example 2.2. If no objects were created, then the number of object created so far would obviously be 0. If you create only one object, then the number of objects created so far would obviously be 1, and so on. In a case like this we need one variable to keep track of the number of objects created. This means that each time that an instance of the class is created, the count of the number of objects is increased by 1. This situation suggests that a class must be used to keep track of the number of objects created, rather than an instance variable.

Let us define a class variable called noOfCircles that will be used to keep track of the number of objects that are produced. Figure 2.4 shows class variable noOfCircles being updated by three objects. The two unattached broken lines illustrate that Object A and Object B have updated the value of the class variable noOfCircles, and Object C currently updates it to three. Notice that there is only one copy of the class variable, regardless of the number of objects created.

Reference

Objects

Figure 2.4 Class variable noOfCircles is updated to three.

Although there are three objects, there is only one copy of the class variable, noOfCircles, quite unlike the instance variable radius, where there are three copies.

Listing 2.2 shows how the class variable noOfCircles is declared and initialized.

1. class areaAndCircumference

2. {

3. private double radius;

4.

5. private static int noOfCircles = 0;

6. }

Listing 2.2 Declaring Class Variable noOfCircles.

When we discuss the topic constructors we will see exactly how this class variable noOfCircles will be updated each time that an object is created.

Exercises (2c)

1. What are member variables?

2. In what section of a class must member variables be declared?

3. Name the two types of member variables discussed in this section.

4. Explain the difference between instance variable and class variable.

5. 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;

6. Have you ever wondered how sports casters can tell the exact number of patrons at a game, even when the arena has several entrances? This is in part how it works. Each person who enters the arena may pass through a different entrance. Each entrance shares a common counting device, which updates the count when a patron passes through any of the entrances into the area.

a) What type of variable would you use to represent the counting device? Explain.

b) What type of variable would you use to represent each entrance? Explain.

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

b) Write the class definition to contain only those variables listed in (7a).

Constants

A constant is a data value that does not change during the execution of the program. Java uses the modifier final to define constants. A constant can be represented by either a class variable or an instance variable. Whichever of the two cases you choose, the identifier that represents a constant must be initialized when it is first declared. Failure to do so will result in compilation error.

The format for defining a constant is as follows:

final data_type nameOfConstant = value;

Or

static final data_type nameOfConstant = value;

In the first case the constant is associated with each instance of the class; but in the second case it is associated with the class as a whole, a class constant.

Let us revisit Example 2.2 and see how this concept fits in context with the class under construction. We know that to find the area and the circumference of circles we need either the diameter or the radius of the circle; or by knowing one, we can find the other. Let us use the radius. In this case the methods for finding the measures are as follow:

• The area of a circle is (r2

• The circumference of a circle is 2(r.

Where (, a fixed value is the ratio of the circumference of a circle and its diameter. Let us approximate the value of ( to 3.14 for this exercise, although Java defines this constant in a class called Math.java. We will explain it later, but for now we will define it ourselves in order to understand the concept of constant.

Let us define the identifier pi as an instance constant, and let us the value 3.14 to pi. Let us apply this concept to the class areaAndCircumference. Figure 2.5 shows that each object has a copy of the constant, pi. I have used heavy bordering to suggest that the value cannot be changed by any of the objects.

Reference

Objects

Figure 2.5 Each object has a copy of the constant, however, none of them is permitted to change the value 3.14.

Frankly, it would be better to make the identifier pi a class constant, because each object is just using the value. If you make it a class constant you would be saving memory. Listing 2.3 shows how the constant identifier pi is incorporated into the class areaAndCircumference as a class constant. Listing 2.3 shows how the identifier pi is defined as a constant.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5.

6. private static final double pi = 3.14;

7. }

Listing 2.3 The identifier pi is defined a constant

In Listing 2.3, Line 6 shows how the identifier pi is defined as a class constant. Notice the use of the keyword, final. Also notice that the identifier is assigned a value; in this case 3.14.

Rules Governing Constants

Exercises (2d)

1. What is meant by the term constant as it pertains to Java programming language?

2. How are constants defined? 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 capacity is 35.

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

Write a class definition to contain these different interest rates as constants. Choose identifier names that match the situation.

Methods

A method is a named self-contained block of codes. Methods add functionality to an object. That is, they define the behavior of the object, by acting upon the variables and using the constants in the class. Another way to express this is that methods algorithmically explain the procedure for manipulating the variables.

There are three types of methods in Java. They are:

• Instance method

• Class method, and

• Constructor

We will study each of them, beginning with instance methods.

Instance Methods

An instance method is one that is associated with each instance (object) of a class. That is, you must create instance of the class in order to invoke or call instance methods. It also follows that you cannot access any instance variable or any class variable via an instance method, if you have not created an instance of the class. Although when you create objects each object gets separate storage space for its instance variables, this is not the case with instance methods. You do not get multiple instance methods, but rather each object shares the same implementation of the instance methods.

The format for defining an instance method is as follows:

return_type Name()

{

Body of method - the algorithm to carry out a procedure

- if applicable

}

Where:

• Modifier could be one or none of these: private, protected, public, and one or both of these: static and final. The modifier final, as it pertains to methods, will not be discussed.

• return_type is any valid data type. Every method must indicate a return type. If a method is not expected to return a value to the caller, then the return type must be coded with the keyword void.

• The identifier Name is the name of the method. The identifier representing the name of a method must follow the naming convention as for variables.

• Parameter represents variable(s) that transport values to the method. You can regard them as conduits that carry data from one part of an object to another; or from a method in one object to deliver to a method in another object. When primitive data values are passed to a method, a copy of it is made by the method that gets it. However, when objects are passed no copy is made. The method simply uses it. If the method changes the state of the object that it gets, then the changes will remain, unless some other method changes its state. Parametric variables are local to the method. They cannot be accessed from outside of the method.

• The body or definition of the method goes between the pair of curly braces. That is, we procedurally explain how to carry out a process using Java statements.

• If the return_type specified in the method declaration is not void, then the return statement is mandatory.

Member methods have direct access to the member variables and member constants of a class, no matter what the access specifiers of the variables are.

Let us go back to Example 2.2 and add the methods findCircumference and findArea. Each method will carry out the calculation and return the calculated value. Recall that the algorithm for calculating the area of a circle is ( . radius2 and the circumference is ( . diameter or 2 . ( . radius. We will use the latter. Listing 2.4 shows how both methods are incorporated into the class.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5. private final double pi = 3.14;

6.

7. public double findArea()

8. {

9. return pi * radius * radius;

10. }

11.

12. public double findCircumference()

13. {

14. return 2 * pi * radius;

15. }

16. }

Listing 2.4 Defining instance methods.

Lines 7 and 12 of Listing 2.4 show the heading for each method. Notice that they both have public access specifiers, and hence can be referenced outside of the current class. In addition both methods are expected to return a numeric value of type double. The Java statement in Line 9 is a compound statement, because it accomplishes two things, namely:

1. It calculates the value for the area of the circle, and

2. It sends back the value calculated to that part of the program that called the method.

The statement in Line 14 has similar functionality as Line 9. The body of each method is enclosed within the pair of curly braces.

Class Methods

Class methods are basically the same as instance methods, except for the following:

1. The implementation of class methods is associated with the class as a whole. They are designed to access class variables without the existence of an instance of the class. Class methods cannot access instance variables, because to access instance variables an instance of the class must be created.

2. When defining a class method, the method name and its associated return data type must be preceded with the keyword, static. See Listing 2.5, Line 17.

3. Class methods cannot return a value represented by an instance variable; the variable representing the value to be returned must either be a class variable, a class constant, or the explicit data value.

Now let us modify our class areaAndCircumference to include a class method that will return the value representing the number of circles that have been processed. Let us call this method getNumberOfCircles (); its role is simply to return the value of the variable noOfCircles. In addition, we make the method public since the value for noOfCircles might be needed outside of the current class. Listing 2.5 represents the modified version of the class areaAndCircumference.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5. private final double pi = 3.14;

6.

7. public double findArea()

8. {

9. return pi * radius * radius;

10. }

11.

12. public double findCircumference()

13. {

14. return 2 * pi * radius;

15. }

16.

17. public static int getNumberOfCircles ()

18. {

19. return noOfCircles;

20. }

21. }

Listing 2.5 Defining a class method

Listing 2.5 Lines 17 – 20 shows the inclusion of the class method getNumberOfCircles. Notice the use of the modifier static, which denotes that a class method is being defined. In addition, the variable that is being used to return the value is a class variable. Had we used an instance variable, the compiler would have generated syntax error.

Rules Governing Class Methods

Exercises (2e)

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. Which of the following method signature (header) is correctly expressed?

a) public void int methodA() { …… }

b) private static methodB(){ … }

c) private methodC(){… }

d) public void int methodD(){……}

e) static String(int x){ … }

5. Given the class definition correctMethod below:

a) If an attempt is made to compile the class will it compile successfully? If not, why not?

b) Type it and compile it. Note the response from the compiler and make correction(s) if necessary.

class correctMethod

{

private int x;

private static int y;

public void methodA()

{

x = y;

}

public static void methodB()

{

y = x;

}

}

6. People are paid a gross wage on a bi-weekly basis. From this amount various taxes are deducted in order to get the individual’s net pay.

a) Assume that there is an instance variable called grossPay. What kind of method would you have to write in order to access this variable? Explain.

Given that the following deductions are take from the gross pay each pay period.

• Federal income tax 15% of gross pay.

• Personal savings 5% of gross pay.

• Pension fund 10% of gross pay

• Social security tax 7.5% of gross pay

• Medical insurance $5.00 per employee

• Life insurance $10.00 per employee.

Define a class called bi_weekly_salary and include the following members in the class:

b) Constants that represent each deduction.

c) Member methods to return each of the deductions.

d) Member variable called grossPay.

e) A method to calculate and return the total deduction.

f) A method to calculate and return the net pay.

g) A class variable called noOfEmployees that will keep count of the number of employees that paid deductions.

h) A class method that simply returns the value that would be stored in the class variable noOfEmployees.

i) A class variable called total_grossPay.

j) A class method that simply returns the total gross pay.

Constructors

Constructors are special member methods of a class. They are used to allocate memory for the instance variables declared in the class. Once memory has been allocated, each variable is assigned, whether implicitly or explicitly, an initial value. This means that you must create an instance or object of the class before an instance variable can be used. With respect to class variables, you do not have to create instance of the class in order to use them. The compiler automatically allocates memory for each of them and assigns them their initial value.

The differentiating features between a constructor and a method are:

1. A constructor has the same name as the class.

2. A constructor never returns a value, not even the type void. This means you must not specify a return type.

The format of declaring a constructor is as follows:

Name ()

{

Variable initialization

}

Where:

• Modifier is either: private, protected or public.

• The identifier Name is the name of the class.

• Parameter represents variable(s) that transport data value(s) to the constructor, just like how they work in methods.

• The body or definition of the constructor is enclosed within the pair of curly braces.

Variables that are declared inside the constructor heading are local to the constructor and cannot be accessed outside of the constructor. Similarly, variables that are declared inside the constructor are local to the constructor.

Let us go back to the class areaAndCircumference. In order to find either measurement, the variable radius needs to get value. As we said earlier, constructors receive value(s) that are typically used to initialize the instance variables. Let us define the constructor so that it accepts a single value via the parameter list and assign that value to the variable radius. Constructors can also be used to initialize and update class variables. Listing 2.6 below shows the definition of the constructor that will be used in the class.

public areaAndCircumference(double r)

{

radius = r;

noOfCircles = noOfCircles + 1;

}

Listing 2.6 A possible constructor for the class areaAndCircumference.

Constructors may be place anywhere in the class. However, it is customary to place them immediately following the variable declaration. See Listing 2.7 for how the constructor fits in context of the class.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5. private final double pi = 3.14;

6.

7. public areaAndCircumference( double theRadius )

8. {

9. radius = theRadius;

10. noOfCircles = noOfCircles + 1;

11. }

12. public double findArea()

13. {

14. return pi * radius * radius;

15. }

16.

17. public double findCircumference()

18. {

19. return 2 * pi * radius;

20. }

21.

22. public static int getNumberOfCircles()

23. {

24. return noOfCircles;

25. }

26.

27. }

Listing 2.7 – The class after the constructor has been added.

In Listing2.7 the constructor spans Lines 7 – 11. The constructor heading is on Line 7. Notice that it has the name of the class, and that it is receiving a value via the variable theRadius. This value that is being transported by the identifier theRadius will assigned to the instance variable radius. Line 9 does the actual assignment, and Line 10 updates the class variable noOfCircles each time that the constructor is called; i.e., each time that an object is created.

Exercises (2f)

1. What is a constructor?

2. How do constructors differ from ordinary member methods?

3. Given that Packaging is a class, which of the following would be valid declaration of constructors for the class?

a) public Packaging(int x){ }

b) void Packaging(String x, int y){ }

c) packaging(){ }

d) int Packaging(double x) { }

e) private Packaging() { }

4. People are paid a gross wage on a bi-weekly basis. From this amount various taxes are deducted in order to get the individual’s net pay.

Use the class bi_weekly_salary developed in exercises (2e) No. 6, and write a constructor that takes a single value. Use this value to initialize the instance variable, grossPay.

5. 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 a running total for the day’s sale, and the total number of items purchased for the day.

Requirement:

(a) From the given situation, identify two instance variables; one which represents the sum of each purchase, and the other, the number of items purchased by each customer. Secondly, identify two class variables; one to represent the total sales for the day, and the other to represent the total number of items sold for the day.

(b) Write a class called departmentStore to include the relevant types of variables. Include in the class a constructor that accepts two values; one that represents the customer’s total, and the other representing the number of items bought by an individual. Use the constructor to total the day’s sale and the number of items sold. The class must also provide member methods to return the day’s sale, the number of items sold for the day, the amount spent by each customer, and the number of items that each customer bought.

Creating Objects

Recall that when you define a class, you are merely creating a new data type. Up to this point when you design a class you cannot reference any of the instance variables in the class. In order to refer to any instance variable you must first create an object of the class by calling a constructor to reserve memory for each of its instance variables. This is what creating an object means.

In order to create an object you must do two things:

1. You must declare a variable of the this new type, which we call reference variable, and

2. You must request enough memory for each instance variable.

The format for declaring a variable is as follows:

className referenceVariable;

For instance, consider the following statement:

areaAndCircumference circle1;

This statement simply declares a variable called circle1 of type areaAndCircumference.

This declaration does not allocate memory for any of the instance variables. In general, variable declaration does not reserve memory for any of the instance variable in a class. This declaration simply names a piece of memory circle1, it does not reference any object as yet. See Figure 2.6.

circle1

Figure 2.6 Declaring a variable

In order to create an object of the class, you must use the Java operator, new to allocate sufficient memory for this object. It is only when these two things have been done that an object has been created. At this stage you can refer to any instance methods of the class, which in turn can access any instance variables of the class. The format for creating an instance of a class is as follows:

referenceVariable = new className();

Where:

1. The statement calls a matching constructor of the class.

2. The operator new signals the operating system to allocate sufficient memory for the instance variables in the class.

3. The initial value for each instance variable is passed to the object.

For instance, the following statement creates an object of type areaAndCircumference.

circle1 = new areaAndCircumference(10.0);

Figure 2.7 shows the object circle1 that has been created and the value 10.0 assigned to the variable radius.

circle1

Figure 2.7 The object circle1 has been created and radius is assigned 10.0.

You could populate the memory with more than one object. As a matter of fact you could create as many objects as the amount of memory allows. Each object would have its own copy of the instance variable radius, and each would be set its individual value.

The two statements, declaring the variable and creating the object can be written as one statement. The format is:

className referenceVariable = new className();

In our example, the following statement is equivalent to the two statements that were used to create the object; the one declaring the variable, and the other creating the object.

areaAndCircumference circle1 = new areaAndCircumference(10.0);

Once a class has been defined, it can be compiled, but it cannot be executed by itself unless it contains the method main. Usually we make a test class that has the method main, the entry point to the program. That is, build each class according to the problem definition and then build a test class that implements each class.

Let us write a class called testCircle that will utilize our class areaAndCircumference. This class will contain the method main. Listing 2.8 shows such a class. It simply creates one object.

1. class testCircle

2. {

3. public static void main(String[] arg)

4. {

5. areaAndCircumference circle1 =

new areaAndCircumference(10.0);

6. }

7. }

Listing 2.8 Defining a test class for using the class areaAndCircumference.

Listing 2.8 is the definition for the class testCircle. Line 3 indicates that the class is an executable one, because it has the method main. Line 5 shows how object circle1 is actually created.

Exercises (2g)

1. An object is:

Select the one right answer.

a) The class definition itself.

b) An instance of a class.

c) The declaration of a reference variable.

d) A variable.

2. Given that transportation is a class, how many objects and reference variables are created by the following code?

transportation bus, train;

train = new transportation ();

transportation plane = new transportation ();

3. Use the class definition bi_weekly_salary in Exercise2 (f) question 4, declare two reference variables, and use each of them to create two objects of the class bi_weekly_salary.

4. Use the class definition in Exercise2 (f) question 5, declare two reference variables, and use each of them to create two objects of the class you designed.

Calling Methods

Methods are used to access the variables and constants that are declared in the class. Remember that class methods can access only class variables and class constants, and that instance methods can access any type of variables and any type of constants. Each method however, has different rules to access each type of variable, as you will see in the next two sections.

Calling Instance Methods

In order to call an instance method you must first create an object. Once the object has been created you can use the reference variable to access any of the instance methods. The format for calling an instance method is as follows:

referenceVariable.instanceMethod( );

For example if you want to call the instance method, findArea(), you first would have to create an object of the class, and then use that object reference to call the method. In this case here is what you would do:

1. Create the object:

areaAndCircumference circle1= new areaAndCircumference();

2. Use the reference variable circle1 to call the method:

circle1.findArea();

Notice the dot ( . ) operator between the object reference and the method name.

Now that we have defined a class, let us use it to produce output. We will divert for a moment to study how to output information from our program.

Producing Output

Java makes available a class called System. This class provides methods for outputting results to the screen. One of the methods is println() and the other is print(). The method println() after placing the output on the current line, moves the cursor to the succeeding line, but print() leaves the cursor on the current line.

The format for each is as follows:

System.out.println();

And

System.out.print();

Where value represents the information that is to be outputted. If there are no data, System.out.println(); leaves the cursor on the succeeding line; but System.out.print(); simply leaves the cursor on the current line.

Two or more values can be joined together to form one value by using the + symbol. Literal values may also be outputted. Listing 2.9 shows a small program called tryit that demonstrates these concepts.

1. class tryit

2. {

3. public static void main(String arg[])

4. {

5. System.out.println("Hello there!");

6. System.out.println(100);

7. System.out.println("Hello there!" + 100);

8. System.out.println("Hello there! " + 100);

9. System.out.print("Hello there! " );

10. System.out.print(100);

11. }

12. }

Listing 2.9 Program tryit demonstrates the use of System.out.println(); and System.out.print();

Figure 2.8 shows the output from the program. Notice that Line 5 of the program corresponds to the first line of output. The second line of output corresponds to Line 6 of the program; and the third line of the output corresponds to Line 7 of the program. Notice the use of the ( + ) that concatenates the two values to form one line of output. Line 8 of the program generates the fourth line of output. Notice the actual space values are also outputted. The lines of outputs discussed so far are generated by System.out.println();. Now notice the last line of output. Lines 9 and 10 generate this line of output. This demonstrates the use of System.out.print();

[pic]

Figure 2.8 Output generated by Listing 2.9

Now that we know how to produce output let us go back to developing the program; and let us apply this concept for outputting the values calculated by the method findArea();

That is, to output the value returned by the call circle1.findArea(); we would write:

System.out.println( circle1.findArea() );

Listing 2.10 shows how to call the instance method and have the value it returns printed. Notice that it is the reference object that must be used to call the instance method findArea(). There is no way to call instance methods than by creating reference objects; and using the reference object to invoke instance methods

1. class testCircle

2. {

3. public static void main(String[] arg)

4. {

5. areaAndCircumference circle1 =

6. new areaAndCircumference(10.0);

7. System.out.println("Area of object 1: " + circle1.findArea() );

8. }

9. }

Listing 2.10 The reference variable is used to call instance method.

Make sure that the both classes (areaAndCircumference and testCircle) are in the same folder. That is Listing 2.7 and Listing 2.10 must be in the same location in order to compile and execute them.

Figure 2.9 shows the output generated by the program. The first line of the output, generated by Line 6 of the program, consists of the literal value Area of object 1: followed by the value 314.0 returned by the method findArea().

[pic]

Figure 2.9. The output from the program.

Calling Class Methods

Class methods are used to access class variables, class constants, or actual data value; but they are never used to access instance variables or constants that are not defined with the modifier static. To access class variables using a class method, you simply use the class name to call the method. The format for calling a class method using the class name is as follows:

className.nameOfClassMethod(< parameter>);

In our example the following statement calls the class method, getNumberOfCircles() without creating an instance of the class.

areaAndCircumference.getNumberOfCircles();

Let us modify the testCircle class to call this method before and after creating the object circle1. That is, make this the first statement and the third action statements in the class. Can you guess what value will be returned by this method? See the first and second line of Figure 2.10 for the answer. Listing 2.11 shows the modification to the class.

Actually we could have used the reference object circle1 to make the second call to the class method getNumberOfCircles()); However, if attempt had been make prior to creating the reference object circle1, syntax error would have been generated.

1. class testCircle

2. {

3. public static void main(String[] arg)

4. {

5. System.out.println("No of objects: " +

areaAndCircumference.getNumberOfCircles());

6.

7. areaAndCircumference circle1 = new areaAndCircumference(10.0);

8.

9. System.out.println("No of objects: " +

areaAndCircumference.getNumberOfCircles());

10.

11. System.out.println("Area of object 1: " + circle1.findArea() );

12. }

13. }

Listing 2.11 Calling class method using the class name.

[pic]

Figure 2.10 The output after including the class method call.

Exercises (2h)

1. How are instance methods called?

2. How are class methods called?

3. Is it possible to call an instance method without creating an instance of the class?

4. Under what condition can a method be called without creating an instance of the class?

5. Write a class for football game scoring. Initially the teams, Maidstone and Mandeville, start with 0 score. Include a method add that adds scores to a team when a team scores; also, a method that gets the total score between both teams at anytime during the match. Provide methods getTeam and getScore to return the name and score for each team, respectively. Write a class to test both teams.

Here is the listing for the class football.

public class football

{

private int score;

private String team;

public football(String name)

{

score = 0;

team = name;

}

public void add(int x)

{

score = score + x;

}

public int getScore()

{

return score;

}

public String getTeam()

{

return team;

}

}

The following is a partial description of the test class.

class testFootball

{

public static void main(String[] arg)

{

football teamA, teamB;

}

}

Use this test class to create the two teams teamA for Maidstone and teamB for Mandeville. The teams score points in the following order: Mandeville 1, Maidstone 3, Mandeville 2, Mandeville 2, Maidstone 2, Mandeville 1, Maidstone 1.

Print the number score before the game begins. Call the add method to add the scores to the respective teams. Print the score again before the end of the game, and finally print the name of each team along with their respective total scores at the end of the game. Figure 2.11 shows a possible output using the given data. Run the program with different sets of data for each team.

[pic]

Figure 2.11 This is an output from the program.

In this lesson we covered the fundamental concepts of the type class.

• A class is a user-defined type. It is used to describe an entity.

• A class encapsulates both the data attributes called member variables, and the member methods, into one complete thought.

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

• The modifier final is used to define a constant.

• Java defines three types of methods: instance method, class method, and constructor.

• Instance methods can only be called if an object is created.

• Class methods can be called without creating instance of the class. This is permissible if no instance variable is involved.

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

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

• Modifiers are used to restrict access to data fields and methods. The modifiers are public, protected, and private.

• Objects are created using the new operator. When an object is created it is given its own chunk of memory.

-----------------------

class name

{

member variables

constructors

member methods

}

Memory

Object A

Object C

Object B

Memory

Object A

radius

radius

Object C

Object B

radius

Memory

noOfCircles = 3

Object A

radius

Object C

radius

Object B

radius

noOfCircles = 3

Memory

Object A

pi = 3.14

radius

radius

Object C

pi = 3.14

Object B

pi = 3.14

radius

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.

1. Class methods MUST be declared with the modifier static.

2. Class methods cannot access identifiers that are not declared with the keyword static.

Memory

radius: 10.0

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download