Java Reference
In-Depth Information
A simple example can help to explain this. Suppose you create a
Dog
class with one method,
bark
,
like so:
class Dog {
void bark() { // Instance method
System.out.println("Woof!");
}
}
Since
bark
is an instance method, you first need to create an object to call it, like so:
Dog myDog = new Dog();
// Call the instance method on the object myDog:
myDog.bark();
That's all there is to defining instance methods. As a reminder, however, recall that methods always
return a type or
void
if they don't return anything. The following example modifies the
Dog
class to
illustrate this once again:
class Dog {
boolean isSitting;
String getBarkSound() {
return "Woof!";
}
boolean isSitting() {
return isSitting;
}
void sit() {
isSitting = true;
}
void stand() {
isSitting = false;
}
}
Note
Note that the
sit
,
stand
, and
isSitting
methods neatly illustrate the
concept of encapsulation, meaning that data in a class (the
isSitting
vari-
able) should be accessed through instance methods (
myDog.sit()
), instead
of directly accessing its variables (
myDog.isSitting = true
). When you learn
about advanced object‐oriented programming concepts in Chapter 8, you
will see how to effectively block accessing instance variables directly, forcing
the use of methods.
Recall that methods returning something (that is, methods that do not return
void
) always need to
include a reachable
return
statement in their body. Note that you can also place
return
statements
in
void
methods. In this case, the
return
statement does not actually return something, but just
Search WWH ::
Custom Search