2. Object-based Programming

advertisement
Object-based Programming
1
COMP 14
Prasun Dewan1
2. Object-based Programming
Now that we have a model of how the computer works; we can address the business-at-hand: how do we program the
computer. Using two simple though realistic examples, this chapter will explain some of the basic elements of a Java
program. It will introduce the concept of style in programming, and identify some of the basic errors to guard against.
It will also explain the process of running a program, that is, converting static program text into active code. After
studying this chapter, you will be able to write a program and run it using ObjectEditor.
Java Objects Vs Real-World Objects
Recall that one of the strengths of Java is the it allows a program to be composed of smaller structures; much as a script
can be broken into smaller units such as sections, paragraphs, and sentences; or a building an be broken up into rooms,
doors, walls, windows, etc. The units of a building are physical objects, while the units of a script are abstract. Like the
latter, the units of a program are also abstract. In fact, part of the challenge of programming will be to understand these
abstractions. To make programming more intuitive (and powerful), Java and other object-based programming
languages provide abstractions, called objects, which are modeled after physical objects. Coding in Java consists
mainly2 of defining and interacting with these program objects.
Since program objects are created by human beings, they are more like manufactured physical objects such as cars and
bicycles, rather than natural objects such as trees and rocks. We interact with a (manufactured) physical object by
performing different kinds of operations on it. For instance, we accelerate, brake, and steer a car. The set of operations
we can perform on the car is determined by the factory that manufactured or defined it. Defining a new kind of car,
thus, involves constructing a new factory for it.
Similarly, we interact with a program object by performing different kinds of operations on it. Performing an operation
on the (program) object is also called invoking or executing or calling the operation; and the operation itself is called a
method. The methods that can be invoked on an object are determined by the class of the object, which corresponds to
the factory that defines the blue print of a manufactured physical object. Defining a new kind of computer object, then,
involves creating or defining or declaring a new class for it. An object is called an instance of its class. Just as a car can
be manufactured on demand by its factory; a computer object can be created on demand by insantiating its class. The
reason for choosing the term “class” for a computer factory is that it classifies the objects manufactured by it. Two
objects of the same class are guaranteed to have the same behavior, much as two cars produced by the same car factory
are expected to work in the same way.
1
2
 Copyright Prasun Dewan, 2000.
In a pure object-based programming language such as Smalltalk, programming consists exclusively of defining and
interacting with objects. As we shall see later, Java is not such a language, since it provides both object-based and
traditional programming. Other books on Java start with traditional programming, whereas, here, we are starting with
object-based programming.
Object-based Programming
2
operations
manufactured by
perform
accelerate
brake
instance of
Class
add
Program
Object
Program
Object
subtract
execute
invoke
call
methods
Figure 0-1 Programming Objects Vs Manufactured Physical Objects
The following table shows the correspondence between these Java concepts and real-world entities.
Java
Class
Computer Object
Method
Invoking/Executing a Method
Instance of a Class
Defining/Declaring a Class
Instantiating a Class
Real-world
Factory
Manufactured Physical Object
Operation
Performing an Operation
Manufactured by a Factory
Constructing a Factory
Manufacturing an Object
Table 1 Java Vs Real-World
A Simple Class
To make these concepts concrete, let us consider a simple class definition:
public class ASquareCalculator
{
public int square(int x)
{
return x*x;
}
}
Figure 0-2 The Class ASquareCalculator
Object-based Programming
3
The class is named ASquareCalculator and it defines a single method, square. This method is a (computer)
function3, which is like a mathematics function in that it maps a set of values, called its domain, to another set of
values, called its range. The two occurrences of int here indicate that both the domain and range of the function is the
set of integers. The line:
return x*x;
indicates that an integer x in the domain is mapped to the square of x (that is, x multiplied with itself) in the range. A
domain value to be mapped is called a parameter of the function and the range value to which it is mapped is called a
result returned by the function. The following figure illustrates the nature of a function:
Domain/Parameter
Values
Range/Result
Values
1
1
2
4
3
9
Mapping
...
...
Figure 0-3 The Square Function
As the figure shows, each of the domain or parameter values is mapped to its square in the range or result values.
The function defined by the class could have also been specified using the more familiar syntax used in mathematics:
square: I  I
square(x) = x2
Why not use this familiar syntax to also write programs? It is difficult to follow this syntax literally while writing a
program because it is designed for handwritten rather than typed text. For instance, in the above example, it is easy to
put the superscript, 2, by hand but not using a word processor. However, there are programming languages, called
functional languages, that define a syntax that is inspired by the mathematics syntax. Unfortunately, Java cannot
support such a syntax because it is far more complex than functional languages, having features that conflict with a
functional syntax.
Interactive Class Instantiation and Method Invocation
What we have done above is define the blueprint of square calculators. To actually manufacture a square calculator, we
must instantiate the class ASquareCalculator. We can then ask the newly created instance to perform the square
operation. Later, we will see how we can write Java code to create an instance of a class and perform operations on it.
For now, we will use ObjectEditor, the tool mentioned in the previous section, to do so interactively. Unlike the editors
you may have used so far, such as notepad or word, it is not an editor of text. Thus, it is not meant for changing the
class. Instead, it allows us to create and manipulate objects. The term, “editor”, thus, might seem like a bit of a
3
We will see the other kind of method, a procedure, in the next chapter.
Object-based Programming
4
misnomer, at this point. Think of it as an object “driver”. Later, when we study properties, you will see that it can also
be used to edit the state of an object.
The following picture shows the user interface of ObjectEditor.
Figure 0-4 Interactively Instantiating ASquareCalculator
To instantiate our example class, all we have to do is enter its name in the Current Class Name text field and
execute the New command from the ObjectEditor menu, as shown in the figure. 4 When it creates a new instance
of the class, ObjectEditor, also creates a new window, shown in Figure 5, to represent the object, which we will
refer to as the edit window of the object. When you learn about properties in the next chapter, you will realize the
reason for text <No Properties> displayed in the window. For now, just ignore it.
Figure 0-5 ASquareCalculator Instance
The window provides the menu, ASquareCalculator, to invoke the square… operation on the object. The …
after the method name indicates that the method takes parameters. (Later, we will see methods without parameters).
When we select the operation, a new window, shown in Figure 6 (a), is created, which prompts the user for a parameter
value, indicating that an integer is expected.
(a)
(b)
Figure 0-6 Specifying the Parameter and Viewing the Result
Be careful not to confuse the New and New… commands. The former instantiates the current class while the latter
prompts for a class name and instantiates the class we specify. Thus, the relationship between these two commands is
similar to the one between the Save and Save As… commands several tools provide to save data in the current and
specified file, respectively.
4
Object-based Programming
5
If we now supply a value and click on the Square button, ObjectEditor calls the method and displays its result
(Figure 6(b)).
Anatomy of a Class
Thus, we have gained a basic understanding of how a class is defined, how a new object of the class is created, and
how an operation on the object is invoked. To gain a more precise understanding, let us consider another problem, that
of computing our Body Mass Index (BMI), which is our weight in kilogrammes divided by the square of our height in
metres. Thus, we need to define a function, let us call it calculateBMI, that maps a weight, height pair to a bmi
value. In Java, a function cannot be defined in isolation; it must be declared in some class, which essentially groups
together a set of related method definitions5. Let us call the class of this function ABMICalculator. We might be
tempted first to write the following class definition:
public class ABMICalculator
{
public int calculateBMI(int weight, int height)
{
return weight/(height*height);
}
}
However, this would require the height, weight, and BMI to be rounded to integers, which we do not want, specially in
the case of height, which recall is measured in metres, and would be rounded to 2 metres for most adults.What we
want, instead, is for each of these to be a real number. Java does undersand a real number, which it calls a double. Thus
we can rewrite the class as:
public class ABMICalculator
{
public double calculateBMI(double weight, double height)
{
return weight/(height*height);
}
}
Figure 0-7 Calculating the BMI
The code follows the pattern we saw in ASquareCalculator. This time, however, we will dissect the class
definition more carefully so that we can explicitly understand the pattern. The following figure shows the various
components of the class definition.
5
In some other languages, such as C++, methods can be defined independently, that is, do not have to part of some
class. By requiring methods to be defined in classes, Java encourages cataloging of methods, an important concern
from the point of understanding a program.
Object-based Programming
Class
Header
Class
Body
6
Method
Header
Method
Body
Parameter
Type
Parameter
Name
1. public class ABMICalculator
2. {
3.
public double calculateBMI(double weight, double height)
4.
{
5.
return weight/(height*height);
6.
}
7. }
Access
Return
Specifier Type
Return
Statement
Return
Expression
Figure 0-8 Anatomy of a Class
The line numbers are not part of the class definition, they have been put so that we can easily identify the class
components.
The class declaration consists of two parts: a class header and a class body. The class header is the first line of the
definition, while the class body is the rest of the definition. The header of a class contains information that is of interest
to its users, that is, ObjectEditor (which is just another class) and other classes that instantiate it. The body of a class,
on the other hand, gives the class implementation. Think of a class user as a customer of a factory and a class header as
information by the factory to potential customers on how to order a product manufactured by it. The class body is the
process that actulally that manufactures the product.
At the minimum, a factory must tell its potential customers that it is a factory, whether they can order products
manufactured by it, and the name they should use to refer to it. This is essentially what the three identifiers in the class
header specify. An identifier is a sequence of letters, numbers, and the underscore character (_) that must begin with a
letter. The third identifier here, of course, is the name of the class. The other two are Java keywords. A keyword is a
predefined Java word, which we will identify using boldface, that has a special meaning to it. It is also called a
reserved word, since it is reserved by the language, can cannot be used for identifiers we invent such as the name of a
class or method. For instance, the reserved word double cannot be used as the name of a class. The keyword class
says that what follows is a class. The keyword public is an access specifier. It says that the class can be accessed by
any other class - in particular ObjectEditor.6 If we omitted this keyword, ObjectEditor would not be able to create a
new instance of the class.
The class body is the implementation of the class, which consists of the definition of the methods of the class enclosed
within the outermost curly braces. In our example, it consists of the definition of a single method, calculateBMI()
(lines 3-6). Like a class declaration, a method declaration has two parts, a header and a body, which gives usage and
implementation information, respectively. The method header is the first line of the method definition (line 3), while
the method body is the rest of the declaration (lines 4-6).
If the keyword were omitted, it would be accessible only to classes in its “package”. It is too early to talk about how
classes are grouped in packages.
6
Object-based Programming
7
A method header is essentially information for a customer who has successfully ordered a factory product and is
interested in actually using the product, that is, invoking operations on it.
It must tell its potential users that is a method, whether they can invoke it, what name they should use to refer to it, how
many parameters it takes, and what are the sets of values to which the parameters and result belong. This is what the
various components of the method header specify. The keyword public again is an access specifier indicating that
the method can be accessed by other classes such as ObjectEditor. If it were omitted, ObjectEditor would not be able to
call the method on an instance of the class. It is useful for a class to be public, but not some of its methods, as we shall
see later. The next keyword, double, is the type of the value returned by the function. A type of a value denotes the
set to which the value belongs; as mentioned above, the type double stands for the set of real numbers. The next
identifier, of course, is the name of the method. It is followed by a list of parameter declarations enclosed within
parentheses and separated by commas. Each parameter declaration consists of the type of a parameter followed by its
name.
A method body defines what happens when the method is invoked. In general, it consists of a series of statements
enclosed within curly braces and terminated by semicolons. A statement is an instruction to the computer to perform
some action. This method consists of a single statement. There are different kinds of statements such as assignment
statements, if statements, and while statements. This statement is a return statement; we shall study other kinds of
statements later. A return statement consists of the keyword return followed by an expression, called the return
expression of the statement. An expression is a piece of Java code that can be evaluated to yield a value. It essentially
follows the syntax of expressions you may have used in mathematics, calculators, and spreadsheets; with a few
differences, such as the use of the symbol * rather than X for multiplication. We will see other differences later.
Examples of expressions include:
1.77
weight
weight*1.77
A return statement asks Java to return the value computed by its return expression as the return value of the function.
Thus, this method body consists of a single statement that returns to its caller the result of evaluating the expression
weight/(height*height).
Bare-Bones Programming Environment
We have seen so far how a class works, but not how it is edited, compiled, or interpreted. The answer depends on the
programming environment we use.
All Java programming environments provide a Java compiler and a Java interpreter, normally called, javac and
java, respectively. In J++, which we shall study in detail later, they are called jvc and jview, respectively.
Moreover, the operating system provides a text editor (such as emacs in Unix environment and notepad in
Windows) and a command interpreter (called a shell in Unix and MS-DOS Prompt in Windows). The
combination of these three tools constitutes a bare-bone programming environment, which is sufficient to develop Java
programs. We will use it for now so that you do not have to bother to learn the complexities of a more advanced
environment, and more important, can understand the exact steps involved in developing and executing a Java
program, which are often hidden by advanced environments.
Many small things can go wrong trying to set up the bare bone environment, which have mainly to do with mistyping
information. The discussion below tells you how to trouble-shoot in case you can make an error. If you still have
problems, you may want to directly try a visual programming environment. The “Visual Programming Environment”
section in the next chapter discusses how J++ can be used to develop a program. The program it illustrates is very
different from this one, but the basic steps to develop the program remain the same.
Downloading ObjectEditor Files
A Java programming environment (bare-bones or visual) does not come with ObjectEditor, which is a tool provided by
the author. It uses three jar files that are not part of the standard Java environment, oe.jar, shapes.jar, and
Object-based Programming
8
swingall.jar. Download these files from www.cs.unc.edu/~dewan/oe. We recommend you make a
directory called Java in your D drive, if you have one, and in the C drive otherwise. In this directory, make a
subdirectory called lib; and in lib, download the three files.
These files are libraries, not executables. Thus, you do not need to open them after you download them. Instead, you
need to specify to the programming environment the locations of these files.
Finding Files
After downloading a file, you may forget its location. Fortunately, the Windows operating system provides the find
command, available from the Start menu, to locate the file. The following figure illustrates how it is used. We can
type the name of the file in the Named field. The command tells us the location of the folder in which the file was
stored.
As we will see later, this command will be very useful when setting up both the bare-bones and Visual J++
environments. (Replace this figure with oe.jar.)
Local Name Vs Full Name of File
The file oe.jar we searched in the figure above, can be referred to by two names: oe.jar and
D:\Java\lib\oe.jar.The first is the local name of the file within the folder in which it is located. The second is
the full name of the file, telling us the location of the file within the computer. In general, the full name of a file is the
name of the folder in which it is stored, followed by the symbol “\”, followed by the local name of the file:
<folder name>\<local name>
Here the two words delimited by < and >, <folder name> and <local name>, are placeholders for actual text you type.
We will often need to enter full name of files. To compose these names, use the find command to determine the name
of their folders, as shown above.
We are now ready to discuss the bare-bones environment.
Program and Class Paths
Object-based Programming
9
Before you use the bare-bones environment, you must ensure that the Java compiler and interpreter are installed on
your computer; and that the folder in which they are installed is in the program path, which is a list of folders in which
the command interpreter searches for programs we name. How exactly you change the program path depends on the
operating system and programming environment. In a Windows environment with J++, create an MS-DOS window.
You can do so by executing the MS-DOS prompt usually available in the Programs menu item in the Start
menu. If it is not in the menu, you can select the Run menu item from the Start menu, and enter the text,
command, as shown below:
In a Windows 987 machine, the program path is specified in the autoexec file. This file has the local name,
autoexec.bat. Use the find command to determine the full name of the file. Now type the following command in
the MS-DOS window to edit this file:
notepad <full name of autoexec.bat>
Usually, the full name of the file is, C:\autoexec.bat. Thus, the command you enter will be:
notepad C:\autoexec.bat
Do not double click on the file in an Explorer window – that will try to execute the lines in the file. You must open it
using a text editor such as notepad.
Now determine the full name of the file, jvc.exe. Next, add the following line to the end of the autoexec file:
SET PATH=%PATH%;<full name of jvc.exe>
%PATH% tells the system to append the new entry to the existing path. Be sure to use ; to separate these entries.
Usually, the full name of this file is C:"\Program Files\Microsoft Visual Studio\VJ98". Thus, you will be adding the the
following line to the end of the file:
SET PATH=%PATH%;C:"\Program Files\Microsoft Visual Studio\VJ98"
The quotes are necessary because the full name contains spaces. The line assumes that J++ has been installed in
C:\Program Files, which is its default location.
The next step is to put the full names of the ObjectEditor files you downloaded in the class path. Like the program
path, a class path is a list of entries that is automatically searched. While the program path is a list of program
directories searched by the command interpreter when we try to execute a program, the class path is a list of jar files,
zip files and directories searched by the Java for library classes.
How the class path is set depends on the operating system. In a Windows 98 environments, like the path, it is specified
in the autoexec file. Use the find command to find the full names of these files, and enter the following line at the end
of the file :
SET CLASSPATH=%CLASSPATH%;.;<full name of oe.jar>;<full name of shapes.jar>;<full name of swingall.jar>
Thus, if you have installed the libraries in D:\Java\lib , add the following line at the end of the file 8:
7
The discussion below assumes Windows 98. It does not apply to a Windows NT machine or a Unix system. Users of
other systems are expected to be more mature and figure out with less handholding what they are supposed to do. In a
Windows NT machine, you must add path and class path entries to the System variable, Environmment. In a Unix
system you must add them to the file .cshrc in your home directory.
Object-based Programming
10
SET CLASSPATH=%CLASSPATH%;.;D:\Java\lib\oe.jar;D:\Java\lib\shapes.jar;D:\Java\lib\swingall.jar
If you have installed the libraries in some other location, you need to enter its name instead of D:\Java\lib in the
file. For instance, if you have saved them in C:\Java\lib, enter the following line:
SET CLASSPATH=%CLASSPATH%;.;C:\Java\lib\oe.jar;C:\Java\lib\shapes.jar;C:\Java\lib\swingall.jar
The . indicates that the current directory should also be searched when looking for classes.
It is possible that when you downloaded the library files, they were converted to zip files: oe.jar.zip,
shapes.jar.zip, and swingall.jar.zip. In this case, you must add the zip extension to the library files:
SET CLASSPATH=%CLASSPATH%;.;D:\Java\lib\oe.jar.zip;D:\Java\lib\shapes.jar.zip;D:\Java\lib\swingall.jar.zip
Figure 9 illustrates what you have to do, showing my auotoexec file before and after the path and class path are set,
assuming the files were not zipped and the software as put in the default directories.
(a) Original Autoexec (C:\autoxec.bat)
(b) Autoexec with Path and Classpath Set
Figure 0-9 Setting the PATH and CLASSPATH
After modifying the autoexec file, restart the computer so that the changes can take effect. Next create the MS-DOS
Prompt window again, and execute the command:
set
Check the values of the path and classpath lists to ensure that they have the entries you added in the autoexec file. The
path variable will have additional entries because of the use of %PATH% to include predefined path entries, as shown
in the figure below. The class path will probably not have additional entries, because the predefined class path is likely
be empty. In this case, %CLASSPATH will be replaced with nothing, and the class path will begin with a semicolon,
as shown in the figure below:
8
If you are using Unix, edit the .cshrc file in your home directory instead of the autoexec file. The syntax for changing
the class path is illustrated below:
set CLASSPATH $CLASSPATH:.: Java/lib/oe.jar:Java/lib/shapes.jar:Java/lib/ swingall.jar
The path is set in a similar fashion.
Object-based Programming
11
If the output of the set command is not consistent with the autoexec file, then you either forgot to restart the computer,
or you did not add entries to set the path and classpath to the end of the file, or you forgot to enter quotes around a full
name containing spaces.
Program Development
We are now ready to illustrate how the BMI program can be developed using a Windows bare- bones environment. We
need to first decide where all the assignments will be stored. Let us assume that this folder is D:\Java.
Begin the process by creating the 14-MOS DOS Prompt window again. Let us assume the current folder displayed
by the MS-DOS window is:
C:\Windows
Change the folder to the drive in which the assignments will be done, by typing the name of the drive:
D:
The current folder will in fact be changed to the last folder visited on the drive. Let us assume it is:
D:\14\notes
Change the current folder to the top-level directory of the drive:
cd ..\..
Each .. allows you to go up one level in the folder structure. In this case, we had to go up two levels, hence we used ..
twice. If the current folder was:
D:\notes
we would have used .. once to reach the root folder:
cd ..
The command, cd, stands for “current directory”, and is so called because a folder was traditionally referred to as a
directory. We shall use these two words interchangeably.
Now change to the folder in which Java programs will be created:
cd java
For each program, create a separate folder for the source and object files of the program. This can be done from the
command interpreter by executing:
mkdir bmi
All subsequent commands will reference this directory; therefore, make it the current directory:
cd bmi
Object-based Programming
12
The next task is to enter the class definition of ABMICalculator in a file. In general, each class should be stored in
a separate file, whose name must be the name of the class followed by the suffix, .java. Therefore, create the file,
ABMICalculator.java, using notepad:
notepad ABMICalculator.java
Now use the text editor to enter the source code of the class. Be sure to use the File menu of notepad to save the file –
the accelerator CTRL-S is not supported by it.
Figure 10 summarizes the steps we have taken so far to create the class file, showing the relationship between the name
of a class and the file in which it is stored.
Figure 0-10 Creating the Source Code of the Class
After entering the source code, compile the class to create the object code of the class (unless a class is compiled, it
cannot be instantiated). To compile a class, type the name of the compiler (javac or jvc) followed by the name of the
file containing the class source code. If you have J++ installed, type the following command:
jvc ABMICalculator.java
If you get the message, “Bad command or file name”, look at the footnote below.9 The compiler will report any errors
it finds, indicating, for each error, the location of the error within the source file. For example, it may report the error:
9
If this command does not succeed, execute the command without the file name:
jvc
If this command succeeds, and the previous one did not, then check that you have entered the file name correctly and
are in the directory in which the file was created. If this command also does not succeed, then look at the autoexec file
to check that you entered the line to set the path correctly. In particular, use the find command to determine that you
Object-based Programming
13
ABMICalculator.java(2,23) : error J0012: Expected ';'
to indicate a missing “;” in the 23rd character of line 2 of the source file.
The compiler stores the object code of the class in the file ABMICalculator.class. Verify that the file has in
fact been created by executing the command:
dir
The class file will not be created if the source file has any errors or is empty (which could happen if you did not save
the file.)
The class, ABMICalculator, is not a complete program, because it does not contain a “main method,” which is the
first method executed in a program. It is a bit too early to fully understand and write a main method; it is for this reason
we used ObjectEditor in the first example, which supplies a main method that allows us to create and interact
with instances of any compiled class. We shall continue to use ObjectEditor until we learn how to write our own main
method. As mentioned before, ObjectEditor is just another class. Its full name happens to be
bus.uigen.ObjectEditor. To execute its main method, type the name of the Java interpreter (called jview by
J++ and java by other systems) followed by its name. Thus, in the case of J++, enter the following command. 10:
jview bus.uigen.ObjectEditor
If this command does not succeed, look at the footnote below 11.
entered the full name of jvc.exe correctly. If the autoexec file is correct and Jvc.exe exists, then you probably did
not reboot the computer after changing the autoexec file or forgot to enter quotes around the directory name.
10
Entering such long command lines can be tedious. Fortunately, most command interpreters allow us to re-execute
commands we have entered before without having to re-enter them. For instance, the up and down arrow keys can be
used in the case of the MS-DOS command interpreter to select a previous command for re-execution.
11
If the error message says that the command name is bad, then check that you entered %PATH% in the autoexec
entry for setting the path.
If the error message says that it could not find the ObjectEditor, then check that you entered its name
(bus.uigen.ObjectEditor) correctly. If you did, check the autoexec entry to set the class path. In particular,
check that each of the three jar files specified in the class path exists and is of the size given in the web page from
which you downloaded the file. You can do so by typing the DOS command, dir, followed by the full name of the
file, which gives the size of the file, if it exists. For instance, if D:\Java\lib\oe.jar is in the class path, type the
command:
dir D:\Java\lib\oe.jar
in the MS-DOS window. You can also find the size of a file by selecting it in an explorer window, right clicking to
bring up the Properties menu, and selecting the General properties.
Object-based Programming
14
Figure 0-11 Compiling the Class and Executing the Interpreter
ObjectEditor print some debugging messages12 in the command interpreter, as shown in Figure 11, which can be
ignored. Once it has printed all of the messages, it displays the user-interface we saw in the first example. Now input
ABMICalculator as the current class name and hit the Enter key. If you get the message:
ClassNotFoundException: ABMICalculator
the class file was not created, which, in turn, means you either forgot to compile the source file or the file has errors or
is empty. You can use the dir command to check if the object class file exists.
Next execute New to create a new instance of the class (Figure 12, left window). ObjectEditor displays an edit window
to interact with the newly created instance. Instead of the menu ASquareCalculator containing the item
Square…, this time the editor offers the menu, ABMICalculator13, containing the item CalculateBMI… (Figure
12, right window).
12
Because Java dynamically searches for a (large number of) library classes when ObjectEditor is executed (rather
than searching earlier when it is compiled), starting it can take a long time. The debugging messages indicate how
much progress it has made so far. Once it starts, it gives fairly fast response.
13
If you do not see a menu for the methods of your class, expand the size of the window. If you still do not see the
menu, you probably forgot to make any of the methods of the class public, as discussed below.
Object-based Programming
15
Figure 0-12 Instantiating ABMICalculator
As before, selecting the menu item creates a dialogue box that prompts for parameter values, displaying the types 14 of
the parameters. This time, there are two slots to fill, because the method takes two parameters.
Figure 0-13 Entering Actual Parameters and Invoking CalculateBMI
Let us enter 74 (Kg) as the first parameter, weight, and 1.77 (meters) as the second parameter, height (Figure 13,
left window). Clicking on the calculateBMI button executes the function and displays the value returned by it
(Figure 13, right window).
Formal Vs Actual Parameters, Variables, Positional Correspondence
We have used the word “parameter”, above, for two distinct but related concepts. We have used it both for the
identifiers, weight and height, declared in the header of the method, and also the values, 74 and 1.77, entered
before executing the method. The former, are in fact, called the formal parameters of the method definition; while the
later are called the actual parameters of the method execution.
A formal parameter of a method definition is a variable, that is a named slot in memory that can hold a value. It is so
called because the value it holds can vary as the program executes. Storing a value in the memory slot of a variable is
called assigning the value to the variable.
An actual parameter of a method invocation, on the other hand, is a value that is assigned to the formal parameter when
the method is executed When an expression containing a formal parameter (or any other variable) is evaluated, the
variable is replaced with the actual parameter assigned to it.
14
The fact that the type names appear in pull down-menus may lead you to believe that you have choice regarding what
type of parameter value is actually input. This is not the case for int or double parameters, but is the case for some other
types of parameters, as we will see when we study interfaces and inheritance.
Object-based Programming
16
public double calculateBMI(double weight, double height)
{
return weight / (height*height);
}
formal parameters
Invoke method
assigned
actual
parameters
variables memory
weight
height
74
0
1.77
0
Figure 0-14 Formal Parameters Vs Actual Parameters
Thus, when the expression:
weight / (height * height)
is evaluated, Java essentially substitutes the two formal parameters with the corresponding actual parameters:
74 / (1.77 * 1.77)
A method can be called several times with different actual parameters; each time different values are assigned to the
formal parameters. Thus, if we invoke the method again with the actual parameters, 80 and 1.8, Java performs the
substitution:
80 / (1.8*1.8)
Java uses positions to establish the correspondence between actual and formal parameters, matching the nth actual
parameter with the nth formal parameter. Thus, we can change the names (but not positions) of the formal parameters
of a method without affecting how we invoke it. An unfortunate side effect is that we must remember the order in
which the formal parameters were declared when invoking the method. Thus, in our example, we must remember that
weight is the first formal parameter and height the second one.
As before, we will continue to use the word parameter for both a formal parameter and an actual parameter, relying on
context to disambiguate its usage. We will also use the term argument for parameter.
Summary of Program Development Process
We can now sum up process we have used so far to define a new kind of object and invoke methods in it:
1.
Start a command interpreter.
Object-based Programming
2.
3.
4.
5.
6.
7.
17
Create a directory in which the source and object file of the class of the object will be stored and change to this
directory.
Create a text file in this directory that contains the source code of the class and whose name is the name of the
class followed by the suffix, .java.
Compile the source code to create object code, also called byte code.
Ask the Java interpreter to start ObjectEditor, that is, call its main method.
Ask ObjectEditor to create an instance of a class.
Finally, ask ObjectEditor to execute methods in the class.
Figure 15 graphically illustrates the main steps in this process using the BMI program as an example. It shows the
relationships between the four software tools used in this process: the text editor, compiler, interpreter, and object
editor. The text editor creates a class source file that is read by the compiler to create the class object file, which is used
by ObjectEditor to instantiate the class. ObjectEditor is started by the interpreter by executing its main method, which
is responsible creating the user-interface for instantiating a class and invoking methods in the instance.
Text Editor
creates
ABMICalculator
Source Code
ABMICalculator
Instance
reads
Java Compiler
calculateBMI
creates
ABMICalculator
Object (Byte) Code
calls
instantiates
ObjectEditor
main
calls
Java Interpreter
Figure 0-15 Relationships between Text Editor, Compiler, Interpreter, and ObjectEditor
Because ObjectEditor is the program you use to interact with an object, you may feel it is the one responsible for
processing the methods of the object. For instance, in this example, you may feel it is the one that evaluates the
expression to calculate the BMI. As this discussion shows, it is only the “front-end” for invoking the methods. The
methods are processed first by the compiler, which creates the byte code, and then by the interpreter, which interprets
the byte code. In fact, later, you will remove the replace the ObjectEditor with your own front-end.
Errors
So far, we have assumed that everything goes smoothly in the programming process. As you develop your own code,
you will inevitably make errors. As mentioned in the previous chapter, these can be classified into syntax, semantics,
and logic errors.
Syntax errors are errors of form. These errors occur when ungrammatical code is input. For instance, if we forget to
terminate a return statement with a semicolon:
return weight/(height*height)
or use the reserved word double as a class name:
public class double {
Object-based Programming
18
we have created a syntax error. Syntax errors are reported by the compiler, and in advanced programming
environments, by the editor.
Semantic errors occur when the program is grammatically correct but is not meaningful. For instance, if we enter the
following return statement:
return wght/(hght*hght);
we have made a semantic error, since the formal parameters have been named weight and height and not wght
and hght. We will get a message saying that wght has not been declared. An analogous situation would occur if
Shakespeare created the role Juliet but had Romeo referring to her as Julie!
A program may be syntactically and semantically correct, and thus executable, but still not give the correct results. For
instance, if we were to enter:
return weight/height
we have made a logic error, since we did not square the height. Unlike the other errors, logic errors are not caught by
the system - it is our responsibility to check the program for these errors.
class ABMICalculator {
double calculateBMI(double weight, double height)
{
return (height*heigh)/weight
}
Syntax
Error
Semantics
Error
Logic
Error
Access
Error
Figure 0-16 Example Errors
A particular form of logic error you must guard against is an accessibility error, that is an error in the access
specification you have entered for a class or method. For instance, if we omit the public access specifier in the
declaration of ABMICalculator:
class ABMICalculator {…}
and ask ObjectEditor to instantiate the class, we will get an error message indicating that ObjectEditor cannot access
the class (Figure 17). An errors identified while a program is executing is called an exception. The particular form or an
error made here is called an IllegalAccessException.
A similar error occurs if you make the class public, but forget to make its method, calculateBMI, public:
double calculateBMI(double weight, double height) {
return weight/(height*height);
}
This time you will not an explicit error message; instead ObjectEditor will not provide a menu item to invoke the
method on an instance of the class. Since the only method of ABMICalculator is now not public, ObjectEditor
does not even create the method menu ABMICalculator, as shown in Figure 17, right window.
Object-based Programming
19
Figure 0-17 Accessibility Error
In the two examples above, we made the class/method less accessible than it should have been. Of course, it is possible
to make the reverse error of granting a class/method more accessibility than what was intended.
There is another group of errors we need to be concerned with, which are errors users make when interacting with a
program. In this case, the program may be perfectly correct but the user essentially does not speak the right interaction
language. In the example of ASquareCalculator, if we do not use digits for a number, as shown in Figure 18, we
have made a user error. For now, your program does not need to recover from these errors.
Figure 0-18 User Error
You will need to map the editing, compilation, and runtime error messages generated by the system to the actual errors,
which can be a challenging job sometimes and requires some practice. Do not hesitate to ask for help on how to
interpret the error messages.
Case Matters
Figure 19 shows a likely user error. Here we have entered abmicalculator as the name of the class to be
instantiated.
Figure 0-19 Case Matters
This is an error because whenever we refer to an identifier such as a class name, we must spell it exactly the way it was
specified when we declared it. Otherwise Java indicates the exception, ClassNotFoundException. Case matters
in Java names, that is, two identifiers are considered the same if they are spelled the same way and each pair of
corresponding letters have the same case.
Object-based Programming
20
This philosophy may seem confusing, especially after using the Windows operating system, which ignores case in the
names of files and folders. Java forces us to remember the case we used for each letter in a name. As you gain more
experience with programming, you will realize that using case as a basis for creating a unique name can be fairly
convenient. It is confusing and error-prone only if we are not careful in following conventions for choosing names.
Case Conventions
By using conventions, we make the program understandable to ourselves, other programmers, and even a tool such as
ObjectEditor, as we shall see later. Therefore, let us look at two important conventions that have been established for
object-based programs:
 Start the name of a variable (such as a formal parameter) and method with a lower case letter.
 Start the name of a class with an upper case letter.
 To increase readability, we often need to create multi word identifiers. Since spaces cannot be part of an identifier,
separate these words by starting each new word (that is, second and subsequent words) with an upper case letter.
We followed this rule in the identifiers ASquareCalculator, ABMICalculator, and calculateBMI.
The second rule above, of course, determines the case of the first letter of the first word.
As we study other kinds of namable entities such as constants, interfaces and packages, we will extend these
conventions suitably.
Style Principles
These are our first examples of style principles. A style principle is a programming rule that makes our code easy to
understand. It is not enforced by Java, since it is not necessary for making our programs correct. Therefore, it will be
our responsibility to remember and follow all the style principles we identify.
One of the surprising difficulties in programming is choosing appropriate names. Java will allow us to give arbitrary
names, since the choice of a name does not influence the correctness of a program. For example, we could have chosen
C instead of ABMICalculator as the name of the second class. Similarly, we could have chosen x and y instead of
weight and height as the names of formal parameters of calculateBMI.
Such names, however, decrease the readability of the program. Therefore, the identifier you use to name a Java entity
such as a variable or a class should indicate the specific purpose for which the entity has been declared
A disadvantage of this principle is that you have to sometimes type long names. The time you spend doing this will far
outweigh the time you, or more importantly someone else, will spend in understanding the program later.
Case of ObjectEditor Items
As we have seen, ObjectEditor uses the identifiers we have declared in our class as the bases for choosing names of
various items it displays in the user-interface such as the window title, the menu for invoking methods, and items of the
menu. It does not, however, use these identifiers literally; “prettying” them by adding spaces between words and
capitalizing the first letter of identifiers. For instance, the method name, calculateBMI, is translated into the menu
item Calculate BMI. Thus, the names it displays violate the Java conventions we carefully followed in writing
the class. This, however, is not a problem, since those conventions are for programmers trying to understand the code
and not users trying to interact with it; who want aesthetically pleasing user-interfaces. In fact, ObjectEditor allows us
to determine exactly the names used for the displayed items, which may have no correlation with the corresponding
identifiers used in the code. For instance, we can name the item for invoking calculateBMI as Body Mass
Index. The prettying it does is simply its default transformation; it provides a Custom menu to define our own
transformation. How this menu works is beyond the scope of this book.
Summary

Java objects, methods, and classes correspond to real-world objects, the operations that can be performed on them,
and the factories that manufacture the objects, respectively.
Object-based Programming






21
A class definition consists of a class header identifying its name and accessibility; and a class body declaring a list
of methods.
A method definition consists of a method header identifying its name, accessibility, formal parameters, and return
type; and a method body specifying the statements to be executed when the method is called.
Formal parameters of a method are variables to which actual parameters are assigned when the method is called.
The set of values that can be assigned to a formal parameter/returned by a method is determined by the type of the
parameter/method.
The process of writing and executing code we have seen so far consists of declaring one or more methods in a
class, compiling the class, asking the interpreter to start ObjectEditor, asking ObjectEditor to instantiate the class,
and finally, invoking methods on the new instance.
By following style principles in writing code, we make the code more understandable to us, others, and tools such
as ObjectEditor.
Exercises
1.
2.
3.
4.
5.
6.
Define class, method, object, variable, formal parameter, actual parameter, type, statement, return statement, and
expression.
What are the case conventions for naming classes, methods, and variables?
Define syntax error, semantics error, logic error, accessibility error, and user error.
Why is it useful to follow style principles?
Suppose we need a function that converts an amount of money in dollars to the equivalent amount in cents and can
be invoked by ObjectEditor. The following class attempts to provide this function Identify all errors and violation
of case conventions in the class.
class aMoneyconverter {
int Cents (dollars) {
return dollars*100;
}
}
Write and test a function, fahrenheit(), that takes a parameter an integer centigrade temperature and converts
it into the equivalent integer Fahrenheit temperature, as shown in the figures below. Assuming F and C are
equivalent Fahrenheit and centigrade temperatures, respectively, the conversion formula is:
F = C * 9/5 + 32
Implement the function in the class ATemperatureConverter.
(a) Entering Centigrade Temperature
(b) Corresponding Fahrenheit Temperature
Object-based Programming
Figure 20 ATemperatureConverter
Use a bare-bones programming environment to develop and execute the class.
22
Download