VOOZH about

URL: https://www.geeksforgeeks.org/java/instance-methods-in-java/

⇱ Instance Methods in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Instance Methods in Java

Last Updated : 24 Jan, 2026

An instance method belongs to an object of a class and requires an instance to be called. It can access and modify the object’s instance variables and can also call other instance or static methods.

  • Can access and modify instance variables (object state).
  • Can accept parameters and return a value.
  • Can call other instance methods or static methods.
  • Supports encapsulation and object-oriented design.
  • Follows the divide-and-conquer principle in larger applications.

Output
Hello, Alice!

Explanation:

  • greet() is an instance method.
  • It prints the name of the object.
  • Called using an object p of the Person class.

Syntax

modifier return_type method_name( )
{
method body ;
}

  • modifier: It defines the access type of the method, and it is optional to use.
  • return_type:Type of value returned by the method (int, void, String, etc.).
  • method_name: Name of the method.
  • method body: The method body describes what the method does with statements.

Example: Instance Method With Parameter


Output
Sum : 5
GFG!

Explanation:

  • GFG class has an instance method add() that accepts two integers.
  • The method adds the numbers and prints their sum.
  • We create an object and call add() with parameters 2 and 3.

Types of Instance Methods:

There are two types of Instance methods in Java:

1. Accessor Methods (Getters)

Getter methods are used to retrieve the value of a private instance variable. They provide controlled access to object data without allowing modification.


Output
Balance: 100

Explanation:

  • Returns the value of a private instance variable.
  • Provides controlled access to the data.

2. Mutator Methods (Setters)

Setter methods are used to modify or update the value of a private instance variable. They allow controlled updates while maintaining encapsulation.


Output
Balance: 150

Explanation:

  • Modifies the value of a private instance variable.
  • Works together with a getter to control access to data.
Comment
Article Tags:
Article Tags: