Some languages only have functions that are stand-alone (do not belong to classes), for example C. Some languages have both stand-alone functions and methods, for example C++. Java only has methods, which means all methods belong to a class. This is why we have already seen method calls - you cannot do very much without them in Java. There are more details involved in calling methods than what we have covered so far, so let's go over them now.
A method has a specific function to perform and can be called over and over again as needed in your program. Methods are typically called with dot-notation. There are three basic kinds of methods in Java:
object.method(args)
. The object used in the dot-notation must
be of the same class that the method belongs to.
(Read that last sentence again - it is a very important
rule that you must follow!)
For instance, to call the method setLocation() that belongs to the Point class, we must first declare an object of class Point, give it memory and a value with new, and then use that object in the dot-notation. The method manipulates the object used in the dot-notation - for instance setLocation() changes the x and y coordinate for the specific Point object used in the dot-notation.
Class.method(args)
, where the class used in
the dot-notation must be the class the method belongs to. Later in this
module we will look at how to read method signatures. Class methods have the
keyword static in their signature.
Remember that constructors are called with new.
The major difference
between a class method and a regular method is the syntax of the dot-notation.
Class methods are called with Class.method()
and
regular methods are called with object.method()
.
Don't forget that before you can use an object, you must declare it and that the object used in the dot-notation must be an instance of the same class the method belongs to.
When calling a method from inside the same class, do not use dot-notation; you can just call the method directlry.
Many people think of calling a method as "sending a message to the object".
When you call a method, you are telling the object to do something.
For instance, calling p1.setLocation(200, 300);
sends a message
to the object p1, telling it to set its location (x and y coordinates)
to 200, 300.