![]() |
Invoking Class Methods vs. Instance Methods |
In the past, students have been confused about how to invoke
String methods such as length()
and toLowerCase()
,
which are methods you will be using to complete this assignment.
These methods are instance methods on Strings.
Recall that instance methods are methods that are invoked on instances of a class. The syntax for the invocation of instance methods is
<exp>.<method-name>(<argexp_1>,...,<argexp_n>)
where <exp> is an expression that denotes the instance on
which <method-name> is invoked, and <argexp_1> through
<argexp_n> are the argument expressions. For an
instance method you MUST specify an instance before the dot (except
when the instance is this
, in which case it can be omitted.) So if
you want to find the length of the head of an StringList L
,
you write:
head(L).length()
and if you want to lowercase it, you write:
head(L).toLowerCase()
Before the lecture we worked with applications and lists, *all* the
methods you used in the course were instance methods. Things like
forward()
and left()
for buggles,
fd()
and lt()
for turtles,
above()
and beside()
for PictureWorld (note:
these are instance methods of the world, not the pictures!). However,
now that you've seen static methods (i.e., class methods), you have to
be careful to distinguish whether a method is an instance method or a
class method. Class methods have a different invocation syntax,
namely:
<class-name>.<method-name>(<argexp_1>,...,<argexp_n>).
That is, the thing that comes before the dot is the name of the class, and not an expression that denotes an instance.
How do you tell whether a method is an instance method or a class
method? You look at its declaration (i.e., the method header) in the
contract that declares it. If the method header contains the keyword
Static
, it's a class method; if it doesn't contain the
keyword static
, it's an instance method. All the list
and tree methods that we have seen are class methods. Mathematical
operations like Math.max()
and Math.abs()
are class methods. Most operations on strings are instance
methods.
The contracts given for length()
and
toLowerCase()
have the following headers:
public int length() public String toLowerCase()
Because these do not contain the keyword static
, they are
instance methods.
Where do you find the contracts for things like String methods, Math methods, and the like? You look in the Java API (Application Programming Interface) for the version of Java you are using, which is on-line at
http://cs.wellesley.edu/~cs111/contracts/jdk-1.1.8-API/packages.html
(There is also a link to it from the Java documentation home page.) The API is divided into "packages"; most contracts you want are in the java.lang package. For instance, the String contract can be found at
http://cs.wellesley.edu/~cs111/contracts/jdk-1.1.8-API/java.lang.String.html
You should get into the habit of browsing the JDK 1.0.2 API whenever you have questions about Java methods.