Java Class Methods vs. Instance Methods

The Shortcut
2 min readJan 5, 2023

--

In Java, a class method is a method that is defined at the class level and can be called on the class itself, rather than on a specific instance of the class. Class methods are often used to define utility functions that are related to a class, but do not require access to the instance data of the class.

On the other hand, an instance method is a method that is defined at the instance level and can be called on a specific instance of a class. Instance methods typically operate on the instance data of the class and may modify or access the state of the instance.

Here is an example of a class method and an instance method in Java:

class MyClass {
// Class method
public static int sum(int a, int b) {
return a + b;
}
// Instance method
public int multiply(int a, int b) {
return a * b;
}
}

In this example, the sum() method is a class method, because it is defined with the static keyword. This means that it can be called on the class itself, without the need to create an instance of the class.

On the other hand, the multiply() method is an instance method, because it is not defined with the static keyword. This means that it can only be called on an instance of the class, and it has access to the instance data of the class.

To use a class method in Java, you can call it directly on the class, using the following syntax:

int result = MyClass.sum(1, 2);
System.out.println(result);
Output:

3

This code calls the sum() method on the MyClass class and passes the arguments 1 and 2 to it. The result of the call is stored in the result variable.

Note that you cannot call an instance method on a class, because it requires an instance of the class to operate on. You can only call an instance method on an instance of the class, using the following syntax:

MyClass instance = new MyClass();
int result = instance.multiply(3, 4);
System.out.println(result);
Output:

12

This code creates a new instance of the MyClass class called instance and calls the multiply() method on it, passing the arguments 3 and 4 to it. The result of the call is stored in the result variable.

Class methods and instance methods are two different types of methods in Java that serve different purposes and have different characteristics. Class methods are useful for defining utility functions that are related to a class, while instance methods are useful for operating on the instance data of a class.

Find out more about Java here.

--

--

The Shortcut

Short on time? Get to the point with The Shortcut. Quick and concise summaries for busy readers on the go.