What is an instance method in Java, and how can I use one?
I’m still learning about methods in Java and was wondering how exactly you might use an instance method. I was thinking about something like this:
public void example(String random) {
}
However, I’m not sure if this is actually an instance method or some other type of method. Could someone help me understand what an instance method in Java is and how it works?
Hey! Great question.*
Yes, the method you wrote is indeed an instance method in Java because it belongs to an instance of a class rather than the class itself. To use it, you first need to create an object of the class and then call the method. Here’s a quick example:
class Example {
public void greet() {
System.out.println("Hello from an instance method!");
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example(); // Creating an instance
obj.greet(); // Calling the instance method
}
}
Since instance methods require an object to be called, they differ from static methods, which belong to the class itself. 
Great explanation, @miro.vasil
To add on, knowing when to use an instance method in Java is equally important. If you’re working with data that belongs to a specific object (not shared across all instances), you should go for an instance method.
For example, if you have a Car
class, you can define an instance method that describes the details of each car object:
class Car {
String model;
Car(String model) {
this.model = model;
}
public void displayModel() {
System.out.println("This car is a " + model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Tesla Model S");
myCar.displayModel(); // Calls the instance method
}
}
Here, the displayModel()
method is an instance method because it uses the model
variable, which is unique to each car object. This flexibility makes instance methods in Java essential for handling object-specific behaviors. 
One way to really understand instance methods in Java is to compare them with static methods.
Instance Methods require an object to be called. They can access both instance variables and static variables.
Static Methods belong to the class and can be called without creating an object, but they cannot directly access instance variables.
Example:
class Example {
public void instanceMethod() {
System.out.println(“This is an instance method.”);
}
public static void staticMethod() {
System.out.println("This is a static method.");
}
}
public class Main {
public static void main(String args) {
Example obj = new Example();
obj.instanceMethod(); // Instance method needs an object
Example.staticMethod(); // Static method can be called directly
}
}
So, if you need behavior that depends on the specific object’s state, go with an instance method in Java. If it’s a general utility function that doesn’t depend on object properties, make it static.