Chapter IV
Using Class Methods
Chapter IV Topics
4.1 Introduction
4.2 A Brief History
of Program Design
4.3 OOP, a Gentle First Exposure
4.4 Using the Math Class
4.5 Using the Util Class
4.6 Why Object Methods?
4.7 Summary
4.1 Introduction
In Chapter I you were introduced to a history of
program languages. In that brief history
of various languages you were told that C++ is a language with extensive Object Oriented Programming (OOP)
features, but C++ can be written without using any type of OOP. Java on the other hand revolves around
OOP. This means that you need to learn
OOP to write correct Java programs and OOP needs to be introduced early in the
computer course.
OOP can easily overwhelm the new computer science
student with a sizable vocabulary of obscure words along with even more obscure
definitions for those words. Words like encapsulation, inheritance and polymorphism
are not intuitive household words for the average person. It is the aim of Exposure Java to give you a
very thorough treatment of all the various OOP concepts. However, these concepts will be introduced
one small chunk at a time. OOP may be a
formidable challenge to comprehend, but all challenges can be broken down into
small manageable parts. This short
chapter is but one small stage along the road to master computer science with
the Java programming language. You will
also find that future chapters will repeat prior concepts frequently to
reinforce what was learned earlier.
Object Oriented Programming is now an established
computer science style of programming that is making the demands of today's
computer programs possible. You will
also find OOP in future college courses as well as in the computer application
programs that surround us. Thinking
about objects and using all types of objects has infiltrated practically every
area of technology.
4.2 A Brief History
of Program Design
You are learning computer science with a strong
emphasis on Object Oriented Programming
(OOP). It is not possible to write
any substantial Java program without understanding OOP. You are probably very excited about learning
OOP. It is just too bad that you do not
have a clue what OOP is, where it came from and what its purpose is in your
space-time-continuum.
Answering the what
is OOP question will take this whole course and the next one. Right now, you can learn where it comes from
with little complexity. Consider these
four stages.
|
The Four Stages of
Program Design |
|
· Cryptic Programming Stage · Unstructured, Spaghetti-Programming Stage · Structured Programming Stage · Object Oriented Programming Stage |
The four stages explained here are somewhat of an
over-simplification of the evolution of programming style, but this will do
nicely to give you a brief over- view of where computer science has been and
where it is going.
Cryptic Programming Stage
In the very early days of programming, computers
were incredibly expensive and programmers were very cheap. Computers cost more than one million dollars
and a programmer could be hired for $5,000 a year. Programs were written without any thought
about design. As a matter of fact, many
programs were written intentionally in a very cryptic style that only the
creator of the program could understand.
This style of programming assisted a programmer with job security and it
also stroked egos as only the programmer, the exulted mastermind, could fix or
alter the program at the awe of other less-blessed mortals.
This style of programming did not last long. Computers became cheaper and programmers
became more expensive. Programs required
frequent debugging and updating, and the cryptic style usually meant starting a
program from scratch if the creator left the company. Companies could not afford this wasteful
approach.
Unstructured,
Spaghetti-Programming Stage
The next stage made attempts at being less
cryptic. An effort was started to use
better, meaningful identifiers, comment program code to assist in updating and
provide external documentation for future programmers. But a major problem lurked at this stage in
the form of the goto statement. Programs then and now rarely worked
immediately. Program errors were found
and needed to be fixed and sometimes bugs showed up continuously as the program
aged. A program requires some type of
control sequence, which guides the flow of program execution and in large
programs this program flow would frequently be faulty.
A quick fix was to use a goto statement to put the program back on track. Unfortunately, as programs grew so did the
number of goto statements and large
programs became a maze with program statements linked to other parts in the
program. People unfamiliar with the
design of such a program would often use a pencil and draw the program flow on
a printout of the source code. Such
drawings resulted in a spaghetti appearance of criss-crossing lines and the
term spaghetti programming was born.
Structured Programming Stage
Programs in the past and today have one common goal
that allows no compromise, which is reliability. A program must work correctly. It is nice if a program executes rapidly, but
no amount of speed can excuse a program that is unreliable. The new Denver International Airport that
opened in the late Nineties was delayed considerably by its computerized
luggage handling system. Originally, the
system proved, as it was hoped, to be a marvel of speed. Luggage was handled in a manner never thought
possible. It was true computers added
speed not possible with the simple human process approach. Initially, there was one complaint
though. The system was fast, but the
luggage ended up on the wrong plane.
Never in the history of aviation was luggage lost more rapidly. It took a computer program to achieve that
goal.
Spaghetti programming is a major drawback to
reliability. The many goto statements are basically a quick
band-aid for a flawed program and once there are so many band-aids, the whole
structure becomes weak and very unreliable.
It is no longer possible to have any type of overview of the program
execution.
A new style of programming was developed called structured programming. It is not easy to explain exactly what that
kind of programming involves, but you can realize this. Goto statements
received the boot and were no longer used.
Program flow was strictly controlled with one entrance and one exit and
program statements with a common purpose were grouped together in special
modules. Structured programming greatly
improved the creation, debugging and updating of programming. Reliability was increased along the way.
Object Oriented Programming Stage
Structured programming did just fine in the earlier
world of text-style output. Programs
were simpler and shorter then the later windows-style programs. The incredible complexity of current programs
brought on a new challenge in reliability.
Program users expected programs to look attractive, provide on-line
help, be user-friendly, and yes they still need to be reliable. The length of programs grew incredibly. Many programs in the late Eighties and early
nineties could fit on three to five floppy diskettes. That changed dramatically as today's software
is lucky to fit on one CD. Somehow with
this new magnitude of programming, structured programming could not keep
up. A level of program complexity had
arrived that required a new approach.
This chapter will give a brief introduction to
Object Oriented Programming. Please
accept right now that OOP has many features specifically designed to make a
program easier to develop, simpler to debug and faster to test with
confidence. Program development with OOP
has brought a new level of program reliability.
This also explains why universities have embraced
Java as an introductory programming language.
C++ used to be a popular program language in computer science
classes. C++ has all the powerful OOP
features and C++ was and still is an extremely important language in the computer
science community and software industry.
The key problem with using C++ at the introductory level is that C++ can
be used without OOP at all. In a world
where students need to be thinking about OOP from the beginning, C++ can be
problematic. Java, on the other hand, is
pure OOP. You are not asked if you like
OOP, want to do OOP, oh no, if you program in Java you will be up to your
nostrils in OOP.
4.3 OOP, a Gentle
First Exposure
Textbooks can be so helpful to the young, eager, but
quite confused computer science student.
You, the eager student opens a textbook excited to learn about Object Oriented Programming. Your textbook just oozes the wisdom of the
ages, or at least the last few computer science decades. You just know this wisdom will be uploaded to
your brain by osmosis or some other, equally mysterious process, which is known
as studying in some circles. Actually,
you feel pretty good because you do understand most of the introductory
material that you have been reading. You
have heard about OOP from some people, but you do not have a clue what the hype
is all about. Maybe your textbook will
clarify. In a pretty box you now see the
following definition:
|
Object Oriented Programming (OOP) is a style of programming that
incorporates the three features of encapsulation,
polymorphism and inheritance. |
Well what could be clearer? Encapsulation has always been one of your
hobbies. Polymorphism is a regular topic
around the dinner table and you hope your parents will leave you a nice
inheritance. Why this kind of
vocabulary? Simple. Professions generate vocabulary known to
members of the profession to identify its own members and those outsider lucky
people who need to pay big bucks to acquire the services of the inside
professionals. Doctors, lawyers, accountants,
educators and yes computer scientists all have a set of vocabulary to add
prestige and economics benefits to the profession. Think I am kidding? Consider the following invoice by a network
engineer who fixes a computer network problem.
Repaired
layer-1 radical disruption to the layer-2 NIC, which resulted in a failure of
any frame to identify the appropriate MAC address of the destination host,
while simultaneously disallowing the NIC to perform its usual role of CSMA/CD
of the Ethernet protocol.
Translation: the
network cable was not plugged in.
Now how can you charge $300.00 by stating on an invoice that you plugged
in a cable? OK, back to OOP, and the
whole point of this tangent is to explain that unpleasant vocabulary needs to
be accepted. It comes with any
profession. Do not think that a concept
is complex because the vocabulary sounds intimidating. Professional vocabulary is meant to be
intimidating. Once you work with the
language it is no longer a big deal. So,
now that you have accepted that encapsulation,
polymorphism and inheritance are a way of computer science life, let us see what
this really means.
Forget computer science right now and think object.
What comes to mind? It probably
depends on your age, culture, sex and upbringing but I bet that every object
you think about has nouns and verbs.
What do I mean? Well let us look
at cars. Cars have many objects. They have seats, doors, lights, seat belts,
wheels, radios, engines, transmissions and many other objects that make up the
entire car. Now each one of these
objects has nouns and verbs. Sounds
weird? Consider a radio. A radio has buttons and/or knobs, which can
be pushed or turned. A radio also has a
display screen. A knob, a button, a
display is a noun, and each one of these nouns does something. A knob turns to the right frequency. A button turns the power on and off. The display shows the current frequency or
the CD that is played. The actions
performed by the nouns are the verbs.
Everywhere you look, you are surrounded by many objects. Object Oriented Programming simulates real
life by using a program style that treats a program as a group of objects. Now in OOP we do not use the term nouns and
verbs. You may hear many different terms
being used but currently the more popular terms are attributes and methods. Attributes store program information, which
is like a noun. Methods perform some
actions on the information, which is like a verb. For example, imagine that you have a Student
object. In this object the attributes
are all the student records of information.
The object also contains the ability to sort and display these student
records. Sorting and displaying the
records are methods.
You have already encountered some methods in
Java. Both print and println are
methods. Methods are functions that
perform some task. In the case of print the task is to display
information in a text window.
The significance of Object Oriented Programming is
that attributes and methods are packaged in the same container, the same object
or the same capsule. This accounts for
the name encapsulation. The earlier, non OOP, languages would keep
the attributes, the information stored by a program, separate from the
functions, procedures, actions or methods that process the information.
Do not even try to think about how all this is
achieved. The details come later. This is meant to be an introduction of
general concepts. Where is the reliability
in all this encapsulation business?
Imagine, that you want to have a reliable lumber- yard delivery system. Your job is to drop off large quantities of
lumber at a customer's site. Now this
lumber is very heavy. At the
lumber-yards you have fork lifts to load the lumber. How about unloading the lumber at the
customer location? Perhaps the customer
is at a construction site with a forklift.
Perhaps the forklift is in use, is too large or is too small or maybe
the customer does not have a forklift at
all.
If we keep the lumber (attribute) separate from the
forklift (method) that handles the lumber we may have serious problems
delivering the lumber efficiently and reliably.
The solution is to attach a forklift to the back-end
of the delivery truck. We now have a
delivery object. The object stores the
lumber, moves the lumber and unloads the lumber. Everything required to manage the lumber is
contained in the same object. The
containment or encapsulation of materials or information and the processes that
access the materials is the corner stone of OOP. It increases reliability.
In this chapter no real attempt will be made to
explain polymorphism and inheritance.
Polymorphism means many forms and
that is a topic that is right now not really possible to introduce. Have patience, you need some more tools in
your kit before we can return to that topic.
Inheritance in computer science is very similar to
the meaning of the English word you know.
Something already exists that you acquire for some reason. Inheritance increases reliability
tremendously in programming. Imagine
that you have spent many hours or possibly weeks creating a program that
accomplishes a certain task like a cube that moves in 3d space and can be
controlled with a mouse. It does not
stop with a cube. You want to move on
and control an airplane that moves in 3d space.
It is not necessary to start from scratch because much of what is
necessary for the plane was already done with the cube. In this case you start with the capabilities
of the cube, you inherit them, and then move on to add the requirements of the
plane. The inheritance concept is used a
lot in mathematical definitions, especially in Geometry. Consider a statement like: a
square is a rectangle with four equal sides.
That definition is very short, but only because we inherited all the properties of the
rectangle to define the square.
I believe in exposure as you learned in chapter
one. You did read chapter one I
hope? All these concepts will be
repeated many times and you will be surprised how comfortable the vocabulary
and the concepts behind the vocabulary will become to you before this course is
finished.
You will not get a complete OOP treatment in this
chapter. There will be many separate
chapters devoted to different OOP concepts.
OOP is not trivial computer science, but it is very manageable. We will start early in the course with a
comfortable introduction where you learn to use
classes and objects. In later
chapters you will learn how to design and create your own classes, how to use
inheritance and play around with polymorphism.
At every stage you will appreciate more and more why Object Oriented
Programming is such a powerful computer science concept.
4.4 Using the Math Class
Most students reading this book have little
experience with other programming languages.
Java is considered a relatively small
and simple programming language.
This means that the sum total of its reserved words in Java and the
rules of its syntax are not very large and relatively easy to learn. This only tells part of the story. Computers exists to make life simpler and as
programming computers evolves, it makes sense that an effort is made to
simplify programming.
How does programming become simpler? For starters, programming is simpler when
programs are written is human-type language rather than binary machine code. This process has already been accomplished
for a number of decades. It is in the
nature of human ingenuity to make tools to simplify our lives. It is possible to make large structures with
very few tools, but somebody decided that it would be simpler to constructs
some cranes to help in construction.
Cranes are only a small part because we now have a huge number of tools
for every conceivable construction job.
It is not very different in the computer science
world. It is possible to start each
program by writing code that accomplishes certain required tasks. It is also possible to create libraries of
special program modules that perform a variety of potentially necessary
tasks. Each one of these modules was
designed and written at some prior time, but once written the module is now
available for future use.
It is possible to create a disorganized set of
modules that are scattered around a number of library files. Such is not the nature of OOP. Modules that
perform a related set of functions are grouped together in a special program
type of container, called a class. Java has an absolutely enormous set of
classes for every conceivable purpose.
You will learn more about the organization of all these classes at a
later time. Right now take a look at the
Java Math class. The Math
class contains many useful program modules that compute a wide variety of mathematical functions.
Now you need to understand something. You have already seen program examples that
use simple data types. Manipulating variables
of simple data types requires only the use of the variable identifier and
nothing else. Such is not the case with
classes. You must first specify the
identifier of the class and then use the identifier of the action within the
class. This action, procedure, function,
task, behavior, subroutine, module or whatever you may wish to call it shall in
Java be called a method. Classes contain data and classes contain methods. Program Java0401.java,
in figure 4.1, starts with the sqrt method,
which is an abbreviation for square root.
Figure 4.1
|
// Java0401.java // This program shows how to use the <sqrt> method
of the Math // class. The Math
class is part of the java.lang package, which is // automatically loaded (imported) by the compiler. // Math.sqrt returns the square root of the argument. public class Java0401 { public static
void main (String args[]) { System.out.println("\nJAVA0401.JAVA\n"); int n1 =
625; double n2 =
6.25; System.out.println("Square
root of " + n1 + ": " + Math.sqrt(n1)); System.out.println("Square
root of " + n2 + ": " + Math.sqrt(n2)); System.out.println(); } } |
|
Java0401.java
Output JAVA0401.JAVA Square root of 625: 25.0 Square root of 6.25: 2.5 |
This first program example displays the square root
of two different numbers, n1 and n2.
You need to understand the four important components in the use of a
class method.
|
Class Method Syntax |
|
Math.sqrt(n1) 1. Math is the class identifier, which
contains the methods you call. 2. · separates the class identifier from
the method identifier 3. sqrt is the method identifier 4. (n1) n1 is the argument or parameter passed
to the method |
Maybe after only one program example the four
components do not make much sense. Do
not worry, there are many more examples that will help to clarify this
concept. In particular, you need to
understand the concept of a parameter,
which is used to provide necessary information to a method.
Suppose you say only Math.sqrt? Can Java digest such a
statement? Can you? What do you say when your math teacher walks
up to you and says: "Give me the
mathematical square root!" You
will probably be a little perplexed because the computation of a mathematical
problem requires some type of information.
This information is passed to the method, which can then provide the
requested response.
In the next program example, shown in figure 4.2,
you will see that parameters can be passed in different formats. It is possible to pass a numerical constant,
a variable, an expression or even another method.
Figure 4.2
|
// Java0402.java // This program shows different arguments that can be used
with the <sqrt> method. // Note how a method call can be the argument of another
method call. public class Java0402 { public static
void main (String args[]) { System.out.println("\nJAVA0402.JAVA\n"); double n1,
n2, n3, n4; n1 =
Math.sqrt(1024); //
constant argument n2 =
Math.sqrt(n1); //
variable argument n3 =
Math.sqrt(n1 + n2); // expression argument n4 = Math.sqrt(Math.sqrt(256)); //
method argument System.out.println("n1:
" + n1); System.out.println("n2:
" + n2); System.out.println("n3:
" + n3); System.out.println("n4:
" + n4); System.out.println(); } } |
|
Java0402.java
Output JAVA0402.JAVA n1: 32.0 n2: 5.656854249492381 n3: 6.136518088418903 n4: 4.0 |
|
Method Arguments or
Parameters |
|
The information,
which is passed to a method is called an argument or a parameter. Parameters are
placed between parentheses immediately following the method identifier. Parameters can be
constants, variables, expression or they can be another
method. The only requirement is that
the correct data type
value is passed to the method. In
other words, Math.sqrt(x) can compute the square
root of x, if x is any correct number, but not if x equals "aardvark". |
floor, ceil and round Methods
The Math class has three related methods, floor, ceil and round. You are most likely familiar with rounding to
the nearest integer. Java gives you
several choices of "rounding" numbers.
The name of the method gives a good clue to its
purpose. The floor method returns the next lowest whole number. Think floor
is down. The ceil method returns the next higher whole number. Think ceiling is up. The round method is the traditional
rounding approach, which rounds-up,
if the fraction is 0.5 or greater and rounds-down
otherwise.
Program Java0403.java,
in figure 4.3 on the next page, demonstrates each one of the three different
"rounding" methods.
Figure 4.3
|
// Java0403.java // This program demonstrates the <floor>
<ceil> and <round> methods. // The <floor> method returns the truncation down to
the next lower integer. // The <ceil> method returns the next higher
integer. // The <round> method returns the closest integer. public class Java0403 { public static
void main (String args[]) { System.out.println("\nJAVA0403.JAVA\n"); System.out.println("Math.floor(5.001):
" + Math.floor(5.001)); System.out.println("Math.floor(5.999):
" + Math.floor(5.999)); System.out.println("Math.floor(5.5) :
" + Math.floor(5.5)); System.out.println("Math.floor(5.499):
" + Math.floor(5.499)); System.out.println(); System.out.println("Math.ceil(5.001)
: " + Math.ceil(5.001)); System.out.println("Math.ceil(5.999)
: " + Math.ceil(5.999)); System.out.println("Math.ceil(5.5) :
" + Math.ceil(5.5)); System.out.println("Math.ceil(5.499)
: " + Math.ceil(5.499)); System.out.println(); System.out.println("Math.round(5.001):
" + Math.round(5.001)); System.out.println("Math.round(5.999):
" + Math.round(5.999)); System.out.println("Math.round(5.5) :
" + Math.round(5.5)); System.out.println("Math.round(5.499):
" + Math.round(5.499)); System.out.println(); } } |
|
Java0403.java
Output JAVA0403.JAVA Math.floor(5.001): 5.0 Math.floor(5.999): 5.0 Math.floor(5.5) : 5.0 Math.floor(5.499): 5.0 Math.ceil(5.001) : 6.0 Math.ceil(5.999) : 6.0 Math.ceil(5.5) : 6.0 Math.ceil(5.499) : 6.0 Math.round(5.001): 5 Math.round(5.999): 6 Math.round(5.5) : 6 Math.round(5.499): 5 |
max and min Methods
The first three program examples can easily give the
impression that methods use a single parameter, or at least it appears that
methods of the Math class use a single parameter. In mathematics there are many examples where
a single argument is required in the case of square root, absolute value,
rounding, etc. There are also many
examples where multiple arguments or parameters are used. Many area and volume computations involve
multiple arguments, like the area of a rectangle, which requires length and width. The Java Math class
has two methods, which both require two parameters, max and min. The max
method returns the larger of the two parameters and the min method returns the smaller of the
two arguments. Both methods are shown in
figure 4.4.
Figure 4.4
|
// Java0404.java // This program demonstrates the <max> and
<min> methods. // Math.max returns the largest value of the two
arguments. // Math.min returns the smallest value of the two
arguments. public class Java0404 { public static
void main (String args[]) { System.out.println("\nJAVA0404.JAVA\n"); System.out.println("Math.max(100,200):
" + Math.max(100,200)); System.out.println("Math.max(-10,-20):
" + Math.max(-10,-20)); System.out.println("Math.max(500,500):
" + Math.max(500,500)); System.out.println(); System.out.println("Math.min(100,200):
" + Math.min(100,200)); System.out.println("Math.min(-10,-20):
" + Math.min(-10,-20)); System.out.println("Math.min(500,500):
" + Math.min(500,500)); System.out.println(); } } |
|
Java0404.java
Output JAVA0404.JAVA Math.max(100,200): 200 Math.max(-10,-20): -10 Math.max(500,500): 500 Math.min(100,200): 100 Math.min(-10,-20): -20 Math.min(500,500): 500 |
abs and pow Methods
The abs and
pow methods are not related, but I
did not want to write a program example with a single new method in it, besides
the original sqrt method. The abs
method returns the absolute value of the argument. The pow
method returns a value, which is computed by raising the first parameter to
the power of the second parameter, as shown in figure 4.5.
Figure 4.5
|
// Java0405.java // This program demonstrates the <abs> and
<pow> methods. // Math.abs returns the absolute value of the argument. // Math.pow returns the first argument raised to the power // of the second argument. public class Java0405 { public static
void main (String args[]) { System.out.println("\nJAVA0405.JAVA\n"); System.out.println("Math.abs(-25):
" + Math.abs(-25)); System.out.println("Math.abs(100):
" + Math.abs(100)); System.out.println("Math.abs(0) : " + Math.abs(0)); System.out.println(); System.out.println("Math.pow(3,4)
: " + Math.pow(3,4)); System.out.println("Math.pow(-2,2):
" + Math.pow(-2,2)); System.out.println("Math.pow(2,-2):
" + Math.pow(2,-2)); System.out.println(); } } |
|
Java0405.java
Output JAVA0405.JAVA Math.abs(-25): 25 Math.abs(100): 100 Math.abs(0) : 0 Math.pow(3,4) : 81.0 Math.pow(-2,2): 4.0 Math.pow(2,-2): 0.25 |
PI and E Math Fields
In the majority of cases the only class members that
you use in a program are the class methods.
Most classes do contain data, but such data is normally processed by
methods. There are a few exceptions and
the Math class has two examples. The
values of PI and E are constant mathematical values that
never change. These values are accessed
not with a method call, but something similar, which looks like a method call
without parameters. Look at program Java0406.java, in figure 4.6, and
notice the missing parameters and parentheses.
Now think logically, here. Is a
parameter value necessary to compute PI or
E?
The values never change since they are constant or final as Java calls it. In
this case you are not making a method call, but accessing the data field of the
class directly.