Sub topic 4
Call Static and Instance Methods
In Java, a method is a named set of instructions that can be called, or run. Some methods belong to a class. Others work with a particular object.
A class is a blueprint for creating objects. An object is a thing created from a class. Each object can hold its own data and can use the instance methods defined by its class.
The key difference is:
- A static method belongs to the class. You can call it without creating an object of that class.
- An instance method works with one particular object. An object created from a class is also called an instance of that class.
This difference helps you decide how to call a method and where it gets the data it needs.
Two Ways to Call a Method
Suppose a class named Counter has both kinds of method.
To call a static method, write the class name, a dot, and the method call:
Counter.doubleValue(7)
To call an instance method, use a variable that refers to an object:
first.increment()
Here, first refers to a particular Counter object. The call tells that object to increase its value.
A reference is a value that identifies an object. A variable such as first holds a reference; it does not contain the whole object itself.
Build a Counter Example
The following program creates two counters. Each counter keeps its own value. The program also uses static methods that do not need a particular counter as their starting point.
Save the code in a file named CounterDemo.java.
public class CounterDemo {
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter();
first.increment();
first.increment();
second.increment();
System.out.println("First: " + first.getValue());
System.out.println("Second: " + second.getValue());
System.out.println("Double first: " + first.getDoubledValue());
System.out.println("Double 7: " + Counter.doubleValue(7));
System.out.println("Read first: " + Counter.readValue(first));
}
}
class Counter {
int value = 0;
static int doubleValue(int number) {
return number * 2;
}
static int readValue(Counter counter) {
return counter.getValue();
}
void increment() {
this.value = this.value + 1;
}
int getValue() {
return value;
}
int getDoubledValue() {
return Counter.doubleValue(getValue());
}
}Open a terminal in the folder containing the file. A terminal is a place where you type commands. Run these commands:
javac CounterDemo.java
java CounterDemoThe first command compiles the Java source file. Compiling turns the source code into a form that Java can run. The second command runs the program.
You should see:
First: 2
Second: 1
Double first: 4
Double 7: 14
Read first: 2Follow the Objects
Look at these two lines:
Counter first = new Counter();
Counter second = new Counter();
The word new creates an object. Each line creates a separate Counter object and stores a reference to it in a variable.
Inside Counter, the line int value = 0; declares a field. A field is a variable that belongs to an object or a class. This field belongs to each object, so each counter starts with its own value of zero.
The calls then change the counters:
- The first
first.increment()changes the first counter from zero to one. - The second
first.increment()changes it from one to two. second.increment()changes the second counter from zero to one.
The call on second does not change the first object. That is why their printed values differ.
How Instance Methods Find Their Object
The increment method has no static word in its declaration. It is an instance method:
void increment()
When you call first.increment(), the method works with the object that first refers to. When you call second.increment(), it works with the object that second refers to.
Inside an instance method, this means the current object. In increment, the expression this.value means the value field of that object.
The getValue method uses value without writing this. Java still reads the field from the current object. The two forms, value and this.value, refer to the same field in this method.
An instance method can also call another instance method on the current object. In getDoubledValue, the call getValue() reads the current counter’s value. The method then passes that value to Counter.doubleValue.
The method instructions are defined once in the class. The object used for each call determines which counter’s data the instance method reads or changes.
How Static Methods Work
The static word in a method declaration makes the method a static method:
static int doubleValue(int number)
The call Counter.doubleValue(7) uses the class name. It does not require a Counter object. The method takes a number and returns twice that number.
A parameter is a variable listed in a method declaration. Here, number is a parameter. An argument is a value supplied in a call. In Counter.doubleValue(7), the argument is 7.
Static Methods Can Use Objects
A static method does not have a current object of its own. That does not mean it can never work with objects.
The example’s readValue method accepts a Counter as a parameter:
static int readValue(Counter counter)
Inside that method, counter.getValue() calls an instance method on the supplied object. In main, the call Counter.readValue(first) supplies the first counter. The static method can read that counter because the call gives it a reference to the object.
A static method can also create an object and then call methods on it. What it cannot do is use an instance field or instance method as though there were a current object when none was supplied or created.
For example, writing just value inside doubleValue would not tell Java which counter’s field to use.
Calling Static Methods from Instance Methods
An instance method can call a static method. The example does this in getDoubledValue:
Counter.doubleValue(getValue())
This call has two parts. First, getValue() gets the current object’s value. Then Counter.doubleValue doubles that value.
Use the class name when calling a static method, as this example does. Java also permits some static methods to be called through an object variable, but that style can make the method look like an instance method. The class name makes the distinction clear.
Why `main` Is Static
The program starts with the main method in CounterDemo. The Java launcher looks for this starting method when you run java CounterDemo.
The word static lets Java call main without first creating a CounterDemo object. The String[] args part allows the program to receive text supplied when it starts. This example does not use that text.
Because main is static, it has no current CounterDemo object. It can still create Counter objects, store their references, and call their instance methods.
Choose the Right Kind of Method
Use an instance method when the action needs a particular object’s data. For example, increment changes one counter’s value, so it makes sense as an instance method.
Use a static method when the action does not need a current object. For example, doubling a supplied number does not depend on one counter, so doubleValue can be static.
| Question | Instance method | Static method |
|---|---|---|
| How is it usually called? | Through an object reference, such as `first.increment()` | Through the class name, such as `Counter.doubleValue(7)` |
| Does it have a current object? | Yes | No |
| Can it use a counter’s field? | Yes, on the current counter | Yes, if it has a reference to a counter |
A static method is not always a simple calculation. It may work with objects it receives, as readValue does. Choose based on whether the method needs a current object, not just on whether it does something small.
Common Mistakes
Calling an Instance Method on the Class
Counter.increment() is not a valid call because increment is an instance method. Java needs to know which counter to change.
Create or obtain a counter first, then call the method through its reference, as in first.increment().
Expecting Two References to Mean Two Objects
Creating two objects gives you two separate counters. Assigning one reference to another variable does not create a new object.
For example, after Counter another = first;, both another and first refer to the same counter. Calling another.increment() changes the counter that first also refers to.
Calling an Instance Method Without an Object
A reference can have the special value null, which means it does not refer to an object. Calling an instance method through a null reference causes a NullPointerException: an error that occurs while the program is running.
Make sure the reference points to an object before making the call. In the example, new Counter() creates the object before first.increment() is called.
Practice
Exercise
In the example, why can you call Counter.doubleValue(7) without creating a counter, but not call Counter.increment()?
Show answer
doubleValue is static and needs only the supplied number. increment is an instance method and needs a particular counter to change.
Exercise
After the existing calls to increment, add Counter another = first; and then call another.increment(). What does first.getValue() return?
Show answer
It returns 3. another and first refer to the same counter, so the call changes that counter.
Exercise
Change second.increment() so it runs twice. What values will the program print for First and Second?
Show answer
Both will be 2. The first counter was already incremented twice, and the second counter is now incremented twice as well.