Writing instance methods
Instance methods represent a common behaviour for a whole set of objects belongs to the same class.
In the following code, a class with one instance method
print
is declared:class MyClass {
public void print() {
System.out.println("method");
}
}
The method is called instance method because it doesn't have the keyword
static
in its declaration.An instance method is corresponding to a concrete object of a class and can access its fields.
class MyClass {
int field;
public void print() {
System.out.println(this.field);
}
}
The keyword
this
represents the current instance of the class. It's an optional keyword.Important, instance methods can take arguments and returns a value of any type including the same type as the defined class.
Calling instance methods
To call an instance method, you should create an object of the class.
MyClass object = new MyClass();
object.field = 10;
object.print(); // prints "10"
The code above prints the value of the field of the particular object. The keyword
this
in the class definition represents the object for which the method was called.An example of cats
As a more complex example, let's consider a class for representing cats.
A cat has a name and a state (sleeping or not). A cat can say one of two phrases "meow" or "zzz" depends on the state. When a cat says "meow" it can sometimes fall asleep. The cat can be awakened by invoking the method
wakeUp
.To better understand the methods of the class, read the provided comments.
/**
* The class is a "blueprint" for cats
*/
class Cat {
String name; // the cat's name
boolean sleeping; // the current state of the cat (by default - false)
/**
* The cat say "meow" if he is not sleeping, otherwise - "zzz".
* When a cat say "meow" he can sometimes fall asleep.
*/
public void say() {
if (sleeping) {
System.out.println("zzz");
} else {
System.out.println("meow");
if (Math.random() > 0.5) {
sleeping = true;
}
}
}
/**
* The method wakes the cat
*/
public void wakeUp() {
sleeping = false;
}
}
Now, we can create an instance of a class and invoke its methods. Do not forget, when a cat is created it is not sleeping.
public class CatsDemo {
public static void main(String[] args) {
Cat pharaoh = new Cat(); // an instance named "pharaoh"
pharaoh.name = "pharaoh";
for (int i = 0; i < 5; i++) {
pharaoh.say(); // it says "meow" or "zzz"
}
pharaoh.wakeUp(); // invoking the instance method
pharaoh.say();
}
}
The program's output can be different because of using Math.random()
inside the say
method. Here is an output example:
meow
meow
meow
zzz
zzz
meow
So, instance method allows programmers to manipulate with particular objects of a class and perform some operations.