preface - school of computing and information …smithjo/classnotes_2xxxx/... · web viewname of...

35
Figures..................................................................... 2 Listings.................................................................... 2 Classes and Objects......................................................... 3 Objectives................................................................ 3 Introduction.............................................................. 3 Fundamental Concepts...................................................... 3 Entity.................................................................. 4 Objects................................................................. 5 Defining Classes.......................................................... 8 Variables.............................................................. 10 Identifier............................................................. 11 Rules Governing Identifiers........................................12 Conventions............................................................ 12 Constructors........................................................... 13 Methods................................................................ 15 Accessor Methods................................................... 17 Mutator Methods.................................................... 18 Creating Objects......................................................... 19 How Objects Communicate................................................20 Actual Parameter (Sender)..........................................21 Formal Parameter (Receiver)........................................21 Accessing Methods...................................................... 22 Producing Output......................................................... 23 Developing A Test Class..................................................25

Upload: leque

Post on 21-Aug-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figures............................................................................................................................................................................2

Listings...........................................................................................................................................................................2

Classes and Objects.......................................................................................................................................................3

Objectives...................................................................................................................................................................3

Introduction................................................................................................................................................................3

Fundamental Concepts...............................................................................................................................................3Entity.....................................................................................................................................................................4Objects...................................................................................................................................................................5

Defining Classes........................................................................................................................................................8Variables..............................................................................................................................................................10Identifier..............................................................................................................................................................11

Rules Governing Identifiers.......................................................................................................................12Conventions.........................................................................................................................................................12Constructors........................................................................................................................................................13Methods...............................................................................................................................................................15

Accessor Methods......................................................................................................................................17Mutator Methods.......................................................................................................................................18

Creating Objects.......................................................................................................................................................19How Objects Communicate................................................................................................................................20

Actual Parameter (Sender).........................................................................................................................21Formal Parameter (Receiver).....................................................................................................................21

Accessing Methods.............................................................................................................................................22

Producing Output.....................................................................................................................................................23

Developing A Test Class..........................................................................................................................................25

Page 2: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

FiguresFigure 1 Some attributes and operations of the entity motor car....................................................................................3

Figure 2 Some attributes and operations of the entity Professor....................................................................................3

Figure 3 The attributes and operations of the entity Circle............................................................................................4

Figure 4 Object referenced by Figure 5 Object referenced by........................................................................5

Figure 6 Object for James Nooks refered to Figure 7 Object for Mary Wilson referred.............................6

Figure 8 Object referred to Figure 9 Object referred to......................................................................................6

Figure 10 The general format for describing a class in Java..........................................................................................8

Figure 11 A depiction of the entity Book.......................................................................................................................8

Figure 12 The numeric value 85.95 is stored at the location called price......................................................................9

Figure 13 shows how string variables store their values................................................................................................9

Figure 14 rules governing the naming of identifiers.....................................................................................................10

Figure 15 Convention for naming classes.....................................................................................................................11

Figure 16 Convention for naming variables.................................................................................................................12

Figure 17 Convention for naming methods..................................................................................................................12

Figure 18 The format of a constructor..........................................................................................................................12

Figure 19 Format of a method......................................................................................................................................14

Figure 20 Declaring reference variable called b1.........................................................................................................18

Figure 21 The object referenced by variable b1...........................................................................................................19

Figure 22 Actual parameter and formal parameter must be compatible.......................................................................20

Figure 23 Actual parameter and formal parameter must be compatible.......................................................................20

Figure 24 Output generated by Listing 5......................................................................................................................22

Figure 25 Output generated from the BookStore program...........................................................................................25

Figure 26 Output generated from the Sales program....................................................................................................26

ListingsListing 1 Java code for the class Book............................................................................................................................9

Listing 2 shows the class with four variables – title, isbn, pages and price....................................................................9

Listing 3 Definition of the constructor for the class Book............................................................................................13

Listing 4 Accessor and mutator methods......................................................................................................................16

Listing 5 Demonstrating the use of the println() and print() methods..........................................................................22

Listing 6 The client class BookStore interacts with the class Book............................................................................24

2

Page 3: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Classes and Objects

Objectives1 To understand the concepts of Classes and Objects as they pertain to the subject Object Oriented

Programming.2 To be able to identify objects using everyday experiences3 To learn how to define class in terms of its name, variables, methods, and constructors.4 To differentiate between instance variables and class variables5 To differentiate between instance methods and class methods6 To learn how to create objects of a class.7 To learn how to call methods.8 To develop approach to problem solving using object oriented approach

IntroductionThis lesson lays the foundation for understanding Object Oriented Programming (OOP). It discusses the fundamental concepts of Objects and Classes, and how they relate to Object Oriented Programming. These two concepts form the cornerstone to OOP. In the first section you will learn what an entity is and how it relates to the concept of Class. Secondly, you will learn how to define classes; this is followed by an understanding of what objects are, how to create them, and how to use them. Next, we study how to display information on the screen. The lesson concludes with two examples on program development and problem solving strategies using the object oriented paradigm

Fundamental ConceptsThe Object Oriented Programming paradigm is based on the concept of objects. In terms of natural language, one dictionary defines an object as:

A thing that can be seen or touched; material thing that occupies space. A person or thing to which action, thought or feeling is directed.

From this definition we see that an object is characterized by three properties, namely:1. It has an identity - a name that is unique to it throughout its existence.2. It has properties which distinguish it from other objects, and 3. It has operations that determine its behavior.

Look around you, everything that you see is an object, because everything has a name, has attributes that

characterize it, and operations that determine how it functions.

3

Page 4: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

EntityTo help us understand the concept of objects, we must first understand that the general description of an object is an

entity. Any particular reference to an entity is the object. For instance, one mode of transportation is motor car. This

general description of this form of transport, motor car, is the entity. A Ford Mustang with tag or license plate

901 ALK is a specific motor car. This particular car is an object. For further understanding, let us consider the

following three examples:

Example 1

Figure 1 shows some of the attributes and operations of the entity motor car.

Name of Entity Possible Attributes Possible OperationsMotor car make accelerate

model reverseengine size set cruise controlmaximum speed brake

Figure 1 Some attributes and operations of the entity motor car

Example 2A person who conducts a class is often referred to as a professor. Give this entity a name, and list some attributes

and some operations that best fit a professor.

Solution

A possible name for this entity is Professor. Figure 2 shows some attributes and operations of the entity, Professor.

Name of Entity Possible Attributes Possible OperationsProfessor name conduct research

age teachesqualification grades papersField of study update records

advises students

Figure 2 Some attributes and operations of the entity Professor

These are only a few of the characteristics of the entity, professor. I am sure you can find more.

Example 3

Given the radius of a circle, find its area and circumference. Name the entity and state at least two attributes that are

relevant to it. Also, list at least two operations that are relevant to it.

Solution

4

Page 5: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

A possible name for this entity is Circle. It requires at minimal the radius and pi (π) in order to find its

circumference and its area. Figure 2.3 shows the entity called Circle.

Name of Entity Possible Attributes Possible OperationsCircle radius compute circumference

pi compute area change radius

Figure 3 The attributes and operations of the entity Circle

I have included an operation called change radius. I did so because it is possible that someone might want to change

the area, or the circumference of the circle. To do either, would necessitate changing the radius. Note that at this

point we are not concerned about numerical calculations; rather we are interested in identifying the characteristics of

the entity.

In all three examples, these general descriptions denote the entities. They are like blue print for an actual motor car,

an actual professor, or an actual circle. Object Oriented Programming requires that we recognize the entity – its

name, its attributes, and its operations. Once you have identified the entities and their characteristics, then the rest of

the exercise, writing the code, becomes clear.

ObjectsSo far, we have described what an entity is. The object, however, is as a specific example of the entity, as we

mentioned earlier. We sometimes refer to an object as an instance of the entity. For example, motor car is the entity,

but a Ford Mustang with Vehicle Identification Number (VIN) is a specific instance of motor car. Hence, this

particular vehicle is an object of the entity motor car.

By now you must realize that there are many Mustang cars, and many other make cars such as Hyundai Sonata, or

Toyota Corolla. Each car, however, is uniquely identified by its VIN. In other words, although some cars are built

from the same blue print, each is assigned a unique VIN by the manufacturer. In Object Oriented Programming we

adopt similar principle. That is, many objects may be generated from the same entity, each having the same

attributes and the same operations. Each object, however, must be uniquely identified.

Figure 2.4a and Figure 2.4b show two objects of the entity motor car. There are two major things that you should notice. Firstly, each object is uniquely identified by its VIN, and secondly, each attribute is given a value.

5

Page 6: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figure 4 Object referenced by Figure 5 Object referenced by

VIN: 1200A5020303 VIN: J55500M120502

Going back to Example 2, two instances of the entity Professor could be:

(a) James Nooks, who is 45 years old, has a PhD, and studies Computer Science.(b) Mary Wilson, who is 50 years old, has a MS, and studies Mathematics.

The two professor objects are different because they are separate individuals, and can be referred to by two distinct

social security numbers. In fact, if we use this approach, we could list two people with the same name, and refer to

them by their job number, or by their social security number. In either case, these numbers are unique. By doing so,

there can be no confusion with the identity of the employees, hence, no confusion with objects.

Figure 4 shows the representation of the object for James Nooks, and Figure 5 shows the representation of the

object for Mary Wilson. Notice that each person is uniquely identified by their respective social security number. In

other words, objects are distinct – they occupy their own space. In Object Oriented Programming we use similar

principle whereby each object has a unique identity.

6

make = “Hyundai”model =”Sonata”engine = 2.4color = “gold”efficiency = 27 mpgtank_capacity = 15max_speed = 160

accelerate()brake()setCruiseControl()setRadio()

VIN 120BJ02050003 VIN J55500M120502

make = “Ford”model = “Mustang”engine_size = 5.0color = “black”efficiency = 25 mpgtankCapacity = 12maximum_speed = 120

accelerate()brake()setCruiseControl()setRadio()

Page 7: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figure 6 Object for James Nooks refered to Figure 7 Object for Mary Wilson referred

by SSN: XXX-XX-X500 to by SSN: XXX-XX-600X

In Example 3 there is no obvious way of choosing unique numbers to identity each circle object, as we saw in the

previous two examples. One way to solve this problem is to use names to denote each object. For example, we could

call the objects circle1, circle2, and so on. Against this background we could define two Circle objects as:

(a) circle1 has radius 10 units, and(b) circle2 has radius 25 units

The representations of these two objects are shown in Figure 8 and Figure 9.

Figure 8 Object referred to Figure 9 Object referred to

by the name circle1 by the name circle2

In the foregoing discussion, we have seen that objects are unique. In the case of the object depicting the Mustang,

its identification is VIN 120BJ02050003; for James Nooks, the identification of the object is

7

radius = 25pi = 3.14

calculateArea()calculateCircumference()

radius = 10pi = 3.14

calculateArea()calculateCircumference()

SSN: XXX-XX-X500 SSN: XXX-XX-600X

circle1 circle2

name = “James Nooks” age = 45 qualification = “PhD” fieldOfStudy = “Computer Science”

teaches() conductsResearch() gradesPapers() updatesStudentsRecords()

name = “Mary Wilson”age = 50qualification = “MS”fieldOfStudy = Mathematics”

teaches()conductsResearch()gradesPapers()updatesStudentsRecords()

Page 8: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

SSN: XXX-XX-X500; and in the case of the first circle object, the identification for the object is circle1. This is

the method by which we can know one object different from another. In OOP we refer to each of these names as a

reference to the object.

Exercises a

1. Look around you, write down four entities, and identify each by its name, attributes, and operations, similar

to examples 1 thru 3.

2. State two objects from each of the entities that you named in Question 1.

3. Suppose a company bought an item for certain amount of money and sells it. Do the following:

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

(b) List possible attributes for this entity.

(c) List possible operations for this entity.

(d) List two objects for this entity. That is, give two examples of such a transaction – in terms of the

cost of each item, and amount that each is sold for.

4. 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 attributes for this entity.

(c) List possible operations for this entity.

(d) State two objects for this entity. That is, give two examples for the amount of money, the number of

years, and possible interest rate, for each object.

Defining ClassesNow that we know what entities are, and what objects are, let us see how these concepts fit in context with

programming. Object Oriented Programming languages use the concept of class or some such terminology to denote

entities. In other words, natural language uses the term entity, but Object Oriented Programming uses the term

class. This means that a class, like an entity, has a name, has attributes, and has operations. Similarly, instead of

using the term attribute, the term field is used; and instead of using the term operation, the term method is used.

Figure 10 shows the format for describing a class in Java. The pair of angled brackets indicates that the enclosed

entry is optional.

Figure 10 The general format for describing a class in Java

8

<modifier> class Name{

<modifier> fields<modifier> constructors<modifier> methods

}

Page 9: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

The first line of the format requires at minimum, the Java keyword class followed by the name that you choose for the class. The name can be any name except Java keywords. The fields, the constructors, and methods must appear between the pair of curly braces.

As you read, note the following:

(a) The word class denotes the formation of an entity

(b) The class is given a name. The name can be any name you choose except Java keywords.

(c) The fields which are comprised of variables and/or constants.

(d) The methods which tell how the object behave.

(e) The constructor which puts the object in its initial state.

(f) Modifiers are Java keywords that are used to qualify variables, constants, methods, and constructors. Four

of the more frequently used modifiers are the keywords public, private, static and final

Example 4

Define a class called Book. Let us discuss books in general terms, and let us limit our discussion to four attributes -

the title, ISBN, the number of pages and price. Let us also provide methods to retrieve the price, the isbn, the

number of pages, and the title of each book. We could give names to these methods getPrice, getIsbn, getPages,

and getTitle, respectively. These methods will be designed to provide us information about books. Also, we could

incorporate a method that can be used to change the price of a book if we ever have to. Let us call this method

changePrice. Figure 11 is a depiction of the entity called Book.

Figure 11 A depiction of the entity Book

Let us develop the class. First, we know its name. It is Book. Listing 1 shows a skeletal outline in Java code for the

class Book.

9

Book

titleisbnpagesprice

getTitle()getIsbn()getPages()getPrice()changePrice()

Page 10: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Listing 1 Java code for the class Book

This is an empty class; it has no fields, no constructors, and no methods. Line 1 specifies the name of the class.

Notice the keyword public! When used, it always means that other classes can access the class. The word class is

also a Java keyword. The pair of curly braces defines the body of the class - the class definition.

Remember we have limited our discussion to four attributes of a book - the title, the ISBN, pages, and the price. Let

us specify these names as variable names. See Listing 2.

Listing 2 shows the class with four variables – title, isbn, pages and price

Let us take a closer look at the concept of variables as it applies to Java programming.

VariablesIn Mathematics, we will recall that a variable is a name together with a value associated with it. In programming, we

use similar concept of a variable. For instance, we can draw a box to represent the variable, and inside the box we

can store its value. Figure 12 shows that the numeric variable called price has value 89.95. Numeric variables are

always handled this way.

price

Figure 12 The numeric value 85.95 is stored at the location called price

String variables store their values differently from numeric variables. Figure 13 shows the string variable called

title. It points to (as we would say in programming) a location that contains the value “Learn How to Program”.

10

85.95

1. public class Book

2. {3. 4. }

1. public class Book2. {3. private String title;4. private String isbn;5. private int pages;6. private double

price; 7. }

Page 11: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

title

Figure 13 shows how string variables store their values

String variables always store their values this way; that is, the variable points to a location that contains its value,

instead of storing its value at the location where it is declared.

In Java, a variable must be declared before it can be used. Lines 3, 4, 5 and 6 of Listing 2.2 show the declaration of

the four variables – title, isbn, pages and price. Notice that each declaration consists of four parts

The modifier – private.

A type – which specifies what kind of data each variable will store.

The name of the variable, and lastly

A semi-colon, finishing the declaration of the variable.

The modifier private tells Java that no class other than this class can access these variables. Another feature of Java

requires that you must specify the kind of value a variable will store. For instance, will the variable store a string – a

set of characters, or will it store numbers such integer values, or as decimal values? In the current example we see

that the variables title and isbn will store string values, the variable pages will store integer values, and the variable

price will store decimal values.

A decimal number in Mathematics is called floating point number. Java uses similar concept. In Java floating point

numbers are divided into two groups, one group is called float and the other group is called double. The different

types are used to store different size numbers. These names are keywords. In Mathematics counting numbers are

called integers. In Java they are called int, another keyword. Each variable declaration statement must end with a

semi-colon.

The variables title, isbn, pages, and price are called fields of the class. They are known by the constructors and

methods in the class, as we shall see later. Let us discuss the concept called identifier, as this concept is related to the

names of classes, variables and methods.

IdentifierThe names given to the class, the variables and methods are called an identifier. Java imposes certain rules upon

naming identifiers. Figure 14 shows the rules governing the naming of identifiers.

11

Learn How to program

Page 12: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Rules Governing Identifiers

Figure 14 rules governing the naming of identifiers

The following are valid Java identifiers: PayRate interesT $commission mine2 _good_Identifier

The following are invalid names 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 lowercase letters are considered to be different. Hence the following

pairs of identifiers are not the same.

computerscience computerScience. Payrate payRate generaLaccOUnt generalAccount

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

makes the variables different. These are some of the nuances that beginning programmers have to contend with; but

once you keep practicing, in short time you will overcome them. Associated with identifiers are some conventions

that are adopted in programming.

ConventionsThe Java Specification Language (JSL) describes conventions for Java programmers. These conventions help to

make codes more readable, and avoid certain kinds of name conflicts. Remember that conventions are suggestions

or customary ways of doing things. It does not mean that your program will not work if you do not follow the

12

Identifiers are made up of letters, digits, the underscore ( _ ), and the dollar sign ( $ ) character. They can begin with any of the foregoing except digits.

Identifiers cannot have the space character. Identifiers cannot contain arithmetic symbols, or any punctuation symbols. Keywords cannot be used as identifiers. The characters that make up identifiers are case sensitive.

Page 13: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

conventions. You are urged, however, to use them whenever the opportunity arises. Figure 15 explains the

convention for naming classes in Java.

Figure 15 Convention for naming classes

There are also conventions about choosing names for your identifiers. 16 explains the convention for naming

variables in Java.

Figure 16 Convention for naming variables

Just like how there are conventions for naming variables, there are also conventions for naming methods. Figure 17

explains the convention for naming methods in Java.

Figure 17 Convention for naming methods

Exercises (b)1. Explain how a class is defined in Java. You must account for its name and its components.2. Refer to Exercise (a). Write a partial class definition for Question 3. Supply appropriate name for each

class; also supply appropriate declaration for each variable.3. Implement a partial class definition called Product. The class should have fields such as: name, price,

manufacturer, expiration date, etc.

ConstructorsYou may wonder how the variables that are declared in a class get their initial value. The answer lies in the purpose

of the constructor. The purpose constructors is to create the object by initializing the member variables in the class.

One of the distinguishing features of constructors is that they have the same name as the class in which they are

defined. Other features will be examined as we go along. Figure 18 shows the format of a constructor:

13

JLS proposes that class names should be nouns or noun phrases. The name starts with an uppercase letter and uppercase letter begins each word in the name phrase – as in classes, Book, Circle and MotorCar.

JLS proposes that variable should have names that are nouns, noun phrases, or abbreviations for nouns. The name starts with a lowercase letter, and uppercase letter begins each subsequent word in the name – as in, mine2 and payRate.

JLS proposes that methods should have names that are verb, verb phrases, or abbreviations for verbs. Generally these names reflect the variable name. The name starts with a lowercase letter, and uppercase letter begins each subsequent word in the name – as in, calculate and findCircumference.

Page 14: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figure 18 The format of a constructor

As we said earlier:

Modifiers are optional as indicated by the pair of angled brackets; hence, you could write the constructor

without them.

The identifier Name is the class name.

Parameter represents variables that are used to assign initial values to member variables. The parameter is

optional. If a constructor does not have parameter it is said to be a default constructor. If the programmer

does not supply the initial values then the compiler will assign default values to the variables. Default

values will be discussed in lesson 3.

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

Let us continue to build the class Book, and let us see the role the constructor plays in its development. Listing 3

shows the inclusion of a constructor. It spans Line 7 thru 12.

Listing 3 Definition of the constructor for the class Book

We could assign a specific value to each of the fields in the class Book. However, as you know, different books

have different title, different isbn, different number of pages, and different price. Hence, it would be a better idea to

supply the constructor with these values each time that we want to talk about a particular book. In programming, we

say that the constructor accepts these values and assigns them to the selected field variables.

Let us take a closer look at the constructor for the class, Book. Line 7 shows the constructor heading, called the

constructor signature. Notice that it starts with the keyword public followed by the class name, Book; within the

pair of parentheses are four variables – theTitle, the theIsbn, pages, and thePrice. The value in each of these

14

1. public class Book2. {3. private String title;4. private String isbn;5. private double price; 6.7. public Book (String theTitle, String theIsbn, double thePrice)8. {9. title = theTitle;10. isbn = theIsbn;11. price = thePrice;12. } 13. }

<modifier> name( <parameter> ){

< statements> }

Page 15: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

variables is used to initialize each of the fields. These variables are called parameters. In general, parameters receive

values from outside the current class to initialize member variables, as we will shortly see. The constructor

definition lies between the pair of curly braces. Line 9 shows how the field title is assigned its initial value. Lines 9

thru 11 are called assignment statements. That is, the value in the parametric variable is assigned to the member

variable. An example of this is the statement:

title = theTitle;

This kind of Java statement is the simplest of Java statements. The equal symbol (=) must not be interpreted as

equality as we know it in Mathematics. Rather it means that a copy of the value in the right hand variable is stored in

the left hand variable. Each assignment statement must end with a semi-colon. The variables that are declared inside

the constructor heading cannot be accessed outside of the constructor; not even by the methods in the class. These

variables are said to be local to the constructor. More will be said about local variables in lesson 3.

Exercise (c)1. What is a constructor?2. Given that Packing is a class, which of the following are valid constructor definitions?

(a) public Packing(int x) { }(b) void Packing(String x, int y){ }(c) Packing() { }(d) int Packing(double x) { }(e) private Packing() { }(f) public packing(double x, String y) { }

3. Refer to Exercise (b) Question 3. Write appropriate constructor definition for each of the classes that you

started.

MethodsAs mentioned earlier, methods determine the behavior of objects. That is, they use Java statements to perform

actions on variables. A Java method is classified as either mutator method, or accessor method. A method can be

defined to release information to other classes. Any method that behaves this way is called an accessor method. If

the method does not release information to other classes it is called a mutator method. This distinction between the

types of method reduces the risk of logic error; or if logic errors are present, the effort of finding the error is

reduced. Whether the method is accessor method or mutator method, they both have two things in common. Both

types of methods have a header and a body. Figure 19 shows the format of a method.

15

Page 16: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figure 19 Format of a method.

The method header as illustrated in Figure 19 is the first line of the method definition:

<modifier> data_type methodName( <parameter> )Method header is the gateway through which other methods in the same class and other classes communicate with

the variables in the class. The method may have a modifier such as public, or private, or none at all. However,

every method header must have a type specifier such as double or String. It is the type specifier that determines

whether or not a method is an accessor method or a mutator method. This type specifier must be followed by the

name of the method, followed by optional parameter, similar to the parameter of the constructor. The method

definition must be place between the pair of curly braces.

Listing 4 shows five methods in the class Book, of which four are accessor methods, and one is a mutator method.

The accessor methods are getTheTitle(), getTheIsbn(), getPages(), and getThePrice(); the mutator method is

changeThePrice(double amount).

16

<modifier> data_type methodName( <parameter> ){

<java statements> }

Page 17: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Listing 4 Accessor and mutator methods

We notice that each method header is prefaced with the keyword public. This is means that other classes can access

these methods.

Accessor Methods

Accessor methods as we mentioned earlier release information to other classes. This will always be indicated by:

(a) The method header which tells the type of value that it will release, and

17

1. public class Book2. {3. private String title;4. private String isbn;5. private int pages;6. private double price;7.8. public Book(String theTitle, String theIsbn, , int page, double thePrice)9. {10. title = theTitle;11. isbn = theIsbn;12. pages = page13. price = thePrice;14. }15.16. public String getTheTitle()17. {18. return title;19. }20.21. public String getTheIsbn()22. {23. return isbn;24. }25. public int getPages()26. {27. return pages;28. }29.30. public double getThePrice()31. {32. return price;33. }34.35. public void changeThePrice(double amount)36. {37. price = amount;38. }39. }

Page 18: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

(b) The return statement that will release the value. The return statement must be the last statement in the

method definition.

For example, consider the method getTheTitle() below. The method header Line 14 tells us the type of data it

expects to release. This is indicated by the modifier, String. The return statement, Line 16 specifies that the

variable title will release the information.

14. public String getTheTitle()15. {16. return title;17. }

The word return is a keyword. In this current example, the methods getTheIsbn() and getThePrice() have similar

meanings. Each of these methods has only one statement, the return statement. There are situations however, where

a method may have several lines of codes. This depends on how much actions are to be performed on the variables,

and also the number of variables the method encounters. The last statement in the method, however, must be the

return statement. Any statement that follows the return statement will never be executed; as a matter of fact, the

program will not compile. Finally, the value that is to be returned must match the type indicated in the method

header.

Mutator MethodsMutator methods never release information outside the class. This is indicated by the keyword void in the method

header, as shown in Line 35 below. Mutator methods always use the type modifier void. In addition, the return

statement is never used, as in the case of the method changeThePrice( double amount).

35. public void changeThePrice(double amount)36. {37. price = amount;38. }

In Line 35, the method header shows the use of the keyword void. This method cannot supply any information

outside of this class. Notice that there is no return statement for this method. In this case the method simply carries

out the task of re-assigning the variable, price with a value.

Exercises (d)

1. What would happen if you attempt to compile the following code?

18

Page 19: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

public void methodB(double a){

return 20;}

2. What would happen if you attempt to compile the following code? You may assume that the variable x was already declared.

public double methodB(double a){

x = a;}

3. Refer to Exercise (c), Question 3. Define accessor methods that returns the value represented by each

attribute. Also, include a mutator method that calculates the profit, (assuming profit was made).

Creating Objects

Recall that when you define a class, you have simply written a definition for an entity. Now you are ready to create

objects of the class. To create objects in Java you must do two things, namely:

1. You must declare a variable of this class. This variable is called a reference variable.

2. You must use the Java operator called new, so that the compiler can supply each member variable

sufficient memory. The word new is a Java keyword.

The format for declaring a reference variable is as follows:

className referenceVariable;

For instance, in our current example for the class Book, consider the following declarative statement:

Book b1;This statement simply declares a variable called b1 of type Book. This declaration simply names a memory

location called b1 which will be used to refer to the Book object when it is created. See Figure 20.

b1

Figure 20 Declaring reference variable called b1

As was mentioned, you must use the operator, new, so that the compiler can provide the amount of memory

necessary for each member variable. Only when this is done that you can refer to the instance methods in the class.

The instance methods in turn can access the instance variables in the class. The format for creating an object is as

follows:

referenceVariable = new className(<parameter list>);Where:

19

Page 20: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

1. The statement provides the constructor with data, via the parameter.

2. The operator new signals the compiler to provide memory for the variables

3. The object may be supplied with initial value for each variable, via the constructor.

For instance, the following statement creates a Book object.

b1 = new Book("Learn How to Program", "000-000-00001", 895, 65.95);

Figure 2.17 shows the object that has been created from the class Book. This object is referenced by the variable b1.

Notice that each field in the class is assigned its respective initial value.

Book object

b1

Figure 21 The object referenced by variable b1

You can create as many objects as the amount of memory allows. Each object however will occupy its own space in

memory, and each will have its own copy of the variables title, isbn, pages, and price. The two statements,

declaring the variable and creating the object, can be written as one statement. For instance we could have written:

Book b1 = new Book("Learn How to Program", "000-000-00001", 895, 65.95);

This construct gives the same result as the previous construct.

How Objects CommunicateObjects communicate with each other by passing messages in the form of data. A message is implemented in one of

three ways, namely:

1. The creation of objects when data is sent from one object to another via the constructor.

2. Data is sent from one object to another via methods, and

3. Methods release information to other objects via the return statement.

The first case can be compared to two people, one the sender of message and the other the receiver. The message is

sent by one object (the sender), to the constructor of a class (the receiver), to create the object. In the second case,

the message is sent from one object (the sender) via a method (the receiver). In both cases communication takes the

form of data being passed from one object to another, via constructor or method. In the third case, the return

statement is used to release information. In programming, the data that is being sent is called actual parameter,

20

title = “Learn How to Program”isbn = “000-000-00001”pages = 895price = 65.95

Page 21: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

and the declaration of variables in the header of the receiver is called the formal parameter. In order for

communication to take place, the actual and formal parameters must be compatible. That is:

The number of actual parameters must be the same as the number of formal parameters.

The data types for the actual parameters must be compatible with the data type of the formal parameters.

This means that the data from the sender to the receiver must be in a one-to-one correspondence See Figure 22.

Book b1 = new Book("Learn How to Program", "000-000-00001", 895, 65.95);

public Book(String theTitle, String theIsbn, int page, double thePrice)

Figure 22 Actual parameter and formal parameter must be compatible

Actual Parameter (Sender)The four values: " Learn How to Program", "000-000-00001", 895 and 65.95 are the actual

parameter. These parameters represent the actual data being sent to the constructor.

Formal Parameter (Receiver)The four variables in the declarative statements: String theTitle , String theIsbn, int page and double thePrice are the formal parameters. They receive the variables that will receive and deliver the data to the

respective field in the class Book.

The following scenario represents the second way that objects communicate. The value 105.95 in the sender is the

actual parameter, and the variable amount the receiver is the formal parameter. In this case both parameters know

about the value 105.95. In addition, whenever variables communicate this way, they must follow the same rules as

constructors. See Figure 23.

b1.changeThePrice( 105.95 )

public void changeThePrice(double amount)

Figure 23 Actual parameter and formal parameter must be compatible

21

Page 22: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

In the third case accessor methods communicate with other objects via the return statement as shown in Line 21

below.

19. public String getTheIsbn()20. {21. return isbn;22. }

The kind of data that the method returns must be compatible to the return type specified in the method header. In

this case isbn is of type String, and the return type indicated in the method header is also string, thus establishing

compatibility.

Accessing MethodsClasses interact with other classes by using reference variables. For instance, in the current example, we can use the

reference variable b1 to interact with the class Book. This makes sense, since b1 is the reference variable that was

used to create the Book object. Against this background we can use b1 to access the methods in the class Book. For

instance, the statement

b1.getTheTitle()); shows that b1 interacts with the method getTheTitle()) defined in the class Book. Recall that this method is an

accessor method, designed to provide information to other classes. The statement allows the class Book to release

the title of the book to other objects. Similar meaning can be attached to the statements:

b1.getTheIsbn();b1.getPages();b1.getPrice()

If we wanted to change the price of the book from what it is to $105.85, we would use the method

changeThePrice as shown below.

b1. changeThePrice( 105.85 );

This action causes the method to re-assign the variable price with the value 105.58.

We have seen how to define classes and how classes communicate with one another by passing messages. It is now

time we learn how Java can provide human with information. Before with attempt to use any of the class that we

have discussed, let us divert for a while and see what statements are needed to provide information in general. When

we are done we will return to the class Book and apply the concepts that we learned.

22

Page 23: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Producing Output

Java has a class called System. This class provides access to methods for outputting information to your computer

screen. Two of these methods are println() and print(). The method println() displays a line of information

on the screen and then positions the cursor on the succeeding line. The method, print() simply leaves the cursor in

the current position on the screen after it displays its output. The format for using each of the methods is as follows:

System.out.println(<value>);and

System.out.print(<value>);

where value represents the optional information that is to be outputted. If the value is not a string type, then it is

converted to a string type and outputted.

Two or more values can be concatenated, by using the plus (+) symbol to form a single value. Listing 5 shows a

small program called Printing that demonstrates how information is displayed on the screen.

Listing 5 Demonstrating the use of the println() and print() methods.

23

1. public class Printing2. {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.println("Hello there! " + 100 + 20); 10. System.out.println("Hello there! " + (100 + 20)); 11. System.out.print("Hello there! " );12. System.out.print(100);13. System.out.println();14. }15. }

Page 24: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Figure 24 shows the output from the program.

Figure 24 Output generated by Listing 5

The first line of the output corresponds to Line 5 of the code. It outputs the string value Hello there!, and positions the cursor on the succeeding line of the output.

The second line of output corresponds to Line 6 of the program. It outputs the numeric value 100.

Similarly, it positions the cursor on the succeeding line of the current display.

The third line of output corresponds to Line 7; here the plus (+) sign joins the string “Hello there!” and the

numeric 100 as one string, and outputs it on the same line.

The fourth line of output generated by Line 8 is similar to the output of Line 7 except that some spaces

have been placed between the string value Hello there, and the numeric value, 100.

The output shown on the fifth line was generated by Line 9 of the program. Notice that the numeric value

is concatenated to the string value to form a new string Hello there! 100, including the spaces; and the

numeric value 20 is concatenated to the previous value, resulting in the new string, Hello there! 10020.

The sixth line of output, Hello there! 120, was generated by Line 10. This is how it works. We

introduced the pair of parentheses to carryout the addition of 100 and 20 first. That is, (100 + 20) = 120. This result (120) is concatenated to the string to yield, Hello there! 120.

The last line of output is generated by Lines 11 and 12 of the program. These lines demonstrates the use of

the method, print().

The last println() simply positions the cursor in the next line below the last line of output.

Finally, the last line of text, Press any key to continue …, was generated by the operating system.

This signifies that the execution of this application is completed.

24

Page 25: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

Developing A Test Class

Now that we understand what objects are, and how they are created, let us apply this concept in a test class. Let us

write a client class (test class) called BookStore that will interact with the class Book. Listing 6 shows the class

BookStore. It simply creates one Book object, interacts with the object via methods, and displays information using

concepts that we learned in the previous section.

Listing 6 The client class BookStore interacts with the class Book

Listing 6 defines the client class called BookStore. Line 3 indicates that this class is an executable one because

it contains a special Java method called main. This method serves as the entry point to Java application programs.

This is where execution of the program begins. A single Java application program cannot have more than one class

containing this method, no matter how many classes there are.

Line 5 shows how to create an object of the class Book, and how the object is provided with the actual data the, via

the constructor. This statement means that the variable b1 references the object that was created. You may refer to

Figure 2.12 for a pictorial representation of this concept.

25

1. public class BookStore2. {3. public static void main(String[] arg)4. {5. Book b1 = new Book("Learn How to Program", "000-000-00001", 895, 85.95);6.7. System.out.println("****************************************");8.9. System.out.println("The title of the book is " + b1.getTheTitle());10.11. System.out.println("The ISBN is " + b1.getTheIsbn());12.13. System.out.println("The price is $" + b1.getThePrice());14.15. System.out.println("****************************************");16.17. System.out.println("Change the price of the book");18.19. b1.changeThePrice(105.95);20.21. System.out.println("The title of the book is " + b1.getTheTitle());22.23. System.out.println("The new price is now $" + b1.getThePrice());24.25. System.out.println("****************************************");26. }27. }

Page 26: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

We know how to generate output; let us analyze the output from the BookStore program. In Listing 6 the code on

Line 7 simply outputs a string of forty five or so asterisks (*). Line 9 outputs the string The title is along with the

string value returned by the method getTitle(). Recall that the reference variable b1 refers to the object that was

created from the class Book. This variable is used to communicate with the methods; hence b1.getTitle()

returns the title of books. The output from the program is shown in Figure 25.

Figure 25 Output generated from the BookStore program

Referring to Listing 6, Line 5 creates a Book object that is referenced by the variable b1. Line 7 of the code prints a

string of asterisks (*). Line 9 demonstrates the string – The ISBN is – is concatenated to the value returned by the

method getTheIsbn(). This result is reflected on the second line of Figure 25. The third line of output corresponds

to Line 13 of the code. The codes in Lines 15 and 17 simply display the string shown on Lines 5 and 6 respectively

in the output.

Because the method changeThePrice(….) is a mutator method, it is not expected to return any value, hence no print

statement is associated with it. The reference variable b1 invokes the method. When this is done the method re-

assigns the variable price with the new value. Skipping to Line 23, the new price is reflected as the next to last line

of the output from the program.

Exercises (e)

1. An object is:

(a) The class definition itself.

(b) An instance of a class.

(c) The declaration of a reference variable.

(d) A variable.

Select the one right answer.

26

Page 27: Preface - School of Computing and Information …smithjo/classnotes_2xxxx/... · Web viewName of Entity Possible Attributes Possible Operations Motor car make accelerate model reverse

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. Refer to Exercise (d) Question 3; define a test class called TestSales. Create two objects sale1 and

sale2. Your output should be similar to Figure 26

Figure 26 Output generated from the Sales program

27