CS
99
Summer
2001 7.23
Lecture Notes 7
Reading
5.2, 5.3, 5.5 Savitch
Objects and Constructors
·
An
object is an instance of a class.
·
The
process of creating objects usually involves the following steps:
1. Declaration of a reference variable.
Example:
Triangle t;
2.
Creating
an object.
Example:
t = new Triangle( 3, 4, 5 );
You can also combine the steps in one statement:
Triangle
t = new Triangle( 3, 4, 5 );
·
The
part of the statement after the new keyword is called the
constructor. The only kind of
constructor that comes automatically with each class is the default constructor, which takes no
parameter arguments:
Triangle t = new
Triangle();
Rectangle r = new Rectangle();
·
When
you use this kind of constructor, the instance variables of the class all get
their default values (0 for ints, 0.0 for doubles, false for booleans, null for
Strings, etc ).
·
To
get the constructor to do something more interesting, like assign the various
variables in the class values when you create the object, then you have to
write your own constructor with that express purpose in mind.
·
Indeed,
the main purpose of constructors is
to set the initial state of an object when the object is created using the new operator.
·
A
constructor has the following general syntax:
<constructor header> (<parameter list>) {
<constructor
body>
}
·
In
many ways, a constructor is like a method.
However, it does not return a value; it also must have the same name as the class in which it is defined.
Anatomy of a Method
·
A
method is simply a group of programming language statements that are given a
name.
·
Every
method in Java is part of a particular class.
·
Where
do we put methods? Inside class
declarations like this:
class Whatever {
boolean
method1() {
/*
some code that returns a boolean*/
}
void
method2() {
/*
some code that doesn't return anything */
}
public
static void main( String[] args ) {
/*
main code */
}
}
Here we included method main just to show you that main is a method like any
other. Note that you cannot declare a method inside another
method. It has to go inside a class
declaration at the level shown above.
·
A
method declaration specifies the code that gets executed when a method is
invoked.
·
The
syntax for a method is
[<modifiers>] <return type> <method name>
( <parameters> ) {
<method
body>
}
·
For
example, here is the code for the definition of a method called thirdPower()
that returns the cube of its parameter n:
int thirdPower ( int n ) {
return
n*n*n;
}
·
Let's
examine each of the parts of a method one by one (we'll skip the
[<modifiers>] part and leave that for Wednesday's lecture):
Return type
·
The
return type specified in the method header can be a primitive type, class type,
or the reserved word void.
·
We
use void
when the method doesn't return any value.
·
A
method that returns a value must
have a return statement, and in that return statement it must return an
expression or variable or value that matches the type specified by the method
header. If the method says it returns
an int, you have to do just that.
·
A
return statement consists of the reserved word return followed by an expression
that dictates the value that gets returned.
·
It
is not considered good practice to have more than one return statement in a
method, though it is perfectly legal to do so.
·
In
general, a method should have one return statement as the last line of the
method body, unless that makes the method overly complex.
Method name
·
This
can be anything you want (though it must follow the legal rules for identifiers).
·
It's
considered good Java programming style to always start your method names with a
lowercase letter.
·
Choose
your names so that a reader can guess what your method does just by looking at
it. For instance, if you're writing a
method that translates Strings into PigLatin, you should never call that method
x()
or survivor().
Parameters
·
A
parameter is a value that is passed into a method when it is invoked.
·
A
method definition always gives the parameter list in parentheses after the
method name. If there are no
parameters, an empty set of parentheses is used.
·
The
parameter list specifies the types of the values that are used and the names by
which the method will refer to those parameters.
·
The
names of the accepted parameters are called formal
parameters. For instance, in method
thirdPower() above, n is the formal parameter.
·
When
a method is actually invoked, the values passed into the method are called actual parameters. So if we made the following call with thirdPower():
int cube = thirdPower( 6 );
Then the actual parameter is 6.
·
The
formal parameters are identifiers that serve as variables inside the method and
whose initial values comes from the actual parameters in the invocation. Actual parameters can be literals,
variables, or full expressions that are evaluated and the result passed as the
parameter. So the following calls with thirdPower() are all legal:
thirdPower( 7 ); //
passing a literal
int m = 72;
thirdPower( m ); // passing a variable
thirdPower( (int) (Math.random()*m) );
// passing the result of an expression
·
The
parameter lists in the invocation and the method declaration must match
up! The following two invocations are illegal because thirdPower is expecting
an int, not a String or a double:
thirdPower( "Guantanamera" );
thirdPower( Math.exp( 5 ) );
·
For
methods with more than one parameter, each parameter in the invocation must
match up with the parameters in the declaration, in the order that they're
declared. So a method with the
following header:
void someMethod( int n, String s, boolean b ) {
/* some random code */
}
must, when called, have an int as its first parameter; a String, as its second; and a boolean as its third.
Method Body
·
When
a method is called, the flow of control transfers to that method. One by one, the statements of its method
body are executed. When the method is done, control returns to the location
where the call was made and execution continues.
·
For
instance, consider the method Math.max() which returns the maximum of
the two values that are passed to it (they can be doubles or ints). The body of Math.max() (when the parameters are ints) must look something like
this:
static int max( int x, int y ) {
if
( x > y )
return
x;
return
y;
}
If we have a program segment that does the following:
int m = 5, n = 8;
int z = Math.max( m, n );
/* more statements */
Then before the assignment to z is made the flow of control of wherever that
program segment is sitting transfers to the body of max(
int, int ), and
the statements there are executed.
The actual parameters are 5 and 8; the formal parameters, x and y, will copy
those values: x will be 5, and y will be 8.
Since y is greater than x, y is returned and the value 8 is assigned to
z.
After the assignment is made, the program continues with the statements that
follow the comment.
·
We
can declare local variables in the body of the method for use in that method.
·
These
local variables cannot be accessed from outside of the method, even from other
methods in the same class.
·
The
local variables exist only while the method is executing.
Using Methods
·
There
are three ways we can call methods:
1.
Through
an object reference
Like so:
TokenReader in = new TokenReader( System.in );
int n = in.readInt();
Triangle t = new Triangle( 1, 1, 1 );
if ( t.area() > 10 )
<do something>
2.
Through
the class name, but this only works
for static methods!
Example:
double f = Math.random();
3.
Directly,
using its name. This works only when you use the method in the
class in which it's defined:
Example:
/* in class Triangle */
boolean isScalene() {
return
!isEquilateral() && !isIsosceles();
}
·
The
way you use a method depends on its return type. When the method is of type void, you cannot assign the results of
the method to any variable whatever. Void methods are typically used to perform
an action without reporting to wherever they were called from.
·
When
a method has an return type other than void, then the method can be used to
return a value into any expression where a variable of the same type as the
return type may be used. Look again at
the code involving TokenReader above. in.readInt() returns an int, and its result is assigned
to variable n.