Programming and Problem Solving with Java

(やまだぃちぅ) #1
Here is the syntax template for a call statement:

In Java, methods come in four flavors: instance methods, class methods, helper meth-
ods, and constructors. Instance methods are associated with individual objects. Class (static)
methods, like main, are associated with classes. Helper, or auxiliary, methods are subprograms
within a class that help other methods in the class. Constructors, as discussed earlier, are
used with the newoperator to prepare an object for use.

Instance Methods When we create an object of a given class, it usually has several fields associ-


ated with it. Each object of the class has its own set of these fields, called instance fields.
Because we can have more than one object of a given class, we must designate to which object
the method will be applied, so that the method can access the fields of that particular object.
Stated in object-oriented terms, we must designate to which object the message is being sent.
The object name is appended in front of the method name with a dot in between. In the call

System.out.println(“Good morning.”);

System.outis the name of the object to which the printlnmethod is applied.
Most of our methods are instance methods. Their headings are written without any
special modifiers. For example:

public voidupdateLastName(String lastName)

The use of publichere indicates that we can use the method outside of its class. Because the
class is declared within an application class, “outside” means that it can be accessed by main.
It is not public beyond the application class, so it is not visible to the JVM.

Class Methods When we declare a method with the staticmodifier, it belongs to the class


rather than to objects of that class. Hence it is called a class method.Here’s an example of a
class method heading:

public static voidsetNameFormat(String format)

What does it mean for a method to belong to a class? Such a method is inde-
pendent of all objects instantiated from the class. It does not have access to the
fields of the objects, but rather has access only to those fields that are likewise
declared with the staticmodifier. Such fields are called class fields. Instance
methods have access to both instance fields (fields declared without the static
modifier) and class fields.

Object-Name. Method-Name ( argument , argument... ) ;

Call

(^80) | Java Syntax and Semantics, Classes, and Objects
Class method A method that
belongs to a class rather than its
object instances; identified as
such with the staticmodifier
Class field A field that belongs
to a class rather than its object
instances; identified as such with
the staticmodifier
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf