Methods
A Deeper Look
Chapter 6
What is in this chapter
·
Program modules
·
Static methods and fields
·
The Math class
·
Methods with multiple parameters
·
String Concatenation
·
Ways to call methods
·
The Call Stack & Activation
Records
·
The Java API Package
·
Random-Number Generation
·
Declaring constants
·
Enumerations
·
Scope
·
Method Overloading
Program Modules
Software engineering is a whole branch of computer
science that studies how to make writing programs easier and more error free.
One of the tenets of software engineering is that
program that are modular are easier to write, to modify, and to reuse
Design using modules
If the problem is very large, it should be broken down
into modules.
A module should be a self-contained unit of code.
It should be as independent as possible, with an
interface that communicates with other modules.
Each module should perform a well defined task
It can be developed in isolation from the rest of the
program
Writing modules
Abstraction and information hiding
When you break a problem down into
modules, each module should be a black box
The other modules need to know what goes into the box, and what
comes out (the public part), but do not need to know HOW the transformation
took place
This does several things:
It frees the other modules from
having to know and understand what went on in the other black boxes
It means the writer of each black
box has to concentrate only on how their box works
It means the inside of the box
(the private part) cannot be tinkered with by someone else.
Program modules in Java
Three kinds of modules exist in Java
Methods
Classes
Packages
The Math class
The Math class contains many
common math functions
They all have two things in common
All return a value and
All are called with
Math.methodName()
Included are all the trig
functions
Ceiling, floor, max, min, pow,
sqrt
A look at the Math class in
the Java API
Also included are two constants,
PI and E
To use them, you must include the
class name
Math.PI or Math.E
Writing and calling methods
Writing the method involves both
the header and body
Header: returnType methodName
(argument types)
Body: this is the Java implementation
Example: double add(double num1,
double num2)
{ double result = num1 + num2:
return result;
}
result is a local variable, since it is defined inside the body of the method
The method call is the method
name, and actual arguments
double number1 = 8.8,
number2 = 5.5, sum;
sum = add(number1, number2);.
There are three ways to call a method
Use the method name by itself to call
another method of the same class
If the method was part of an encapsulated
class, call it with an object in front of a dot
Use the class name if it is a static
method like those in the Math class
Example from the text
Look at MaximumFinder on overhead
This is a complete class, with a method called in the
class