0
0
Javaprogramming~5 mins

Instance methods in Java

Choose your learning style9 modes available
Introduction

Instance methods let objects do actions using their own data. They help organize code by connecting behavior to specific things.

When you want each object to perform actions using its own information.
When you need to change or get details stored inside an object.
When you want to keep code organized by grouping actions with the objects they belong to.
When you want to reuse code by calling methods on different objects.
Syntax
Java
class ClassName {
    returnType methodName(parameters) {
        // method body
    }
}

Instance methods belong to objects created from the class.

You call them using the object name, like object.methodName().

Examples
This method bark makes the dog object say "Woof!".
Java
class Dog {
    void bark() {
        System.out.println("Woof!");
    }
}
This method increment adds 1 to the object's count number.
Java
class Counter {
    int count = 0;
    void increment() {
        count = count + 1;
    }
}
Sample Program

This program creates a Car object with a color and then calls the instance method showColor to print the car's color.

Java
class Car {
    String color;

    Car(String color) {
        this.color = color;
    }

    void showColor() {
        System.out.println("The car color is " + color);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("red");
        myCar.showColor();
    }
}
OutputSuccess
Important Notes

Instance methods can use and change the object's own data fields.

You need to create an object before calling an instance method.

Use this keyword inside instance methods to refer to the current object.

Summary

Instance methods belong to objects and use their data.

Call instance methods using the object name.

They help keep code organized and connected to the things it works with.