Java ProgramsOOPInstance Methods

Instance Methods in Java

beginner·  OOP  ·  Classes & Objects

Problem

An instance method is a method that operates on the fields of whichever object it's called on, so calling the same method on two different objects can produce two different results.

Give a Student class a method that checks whether that student is an adult, and call it on two students with different ages.

Input
student1.age = 20, student2.age = 15
Output
Aditi is an adult: true Rohan is an adult: false

Java Program

Java
class Student { String name; int age; boolean isAdult() { return age >= 18; // age here belongs to whichever object called this method } } public class InstanceMethods { public static void main(String[] args) { Student student1 = new Student(); student1.name = "Aditi"; student1.age = 20; Student student2 = new Student(); student2.name = "Rohan"; student2.age = 15; System.out.println(student1.name + " is an adult: " + student1.isAdult()); System.out.println(student2.name + " is an adult: " + student2.isAdult()); } }

Output

Aditi is an adult: true Rohan is an adult: false

Core Logic

Writing isAdult() to read the calling object's own age field, rather than a fixed value, means the same method call answers differently depending on which object it's called on.

How It Works
  1. 1boolean isAdult() is declared inside Student, with no parameters of its own.
  2. 2Inside the method, age refers to whichever object's age the method was called on — Java resolves this through an implicit this reference.
  3. 3student1.isAdult() reads student1's own age, and student2.isAdult() reads student2's own age, independently.
  4. 4The method's logic never changes — only which object's data it's reading changes between calls.
With student1.age = 20 and student2.age = 15, the exact same isAdult() call returns true for one and false for the other.
💡

Key Point: An instance method needs an actual object to be called on — there's no standalone isAdult() to call without deciding whose age it should check.

Key Concepts

instance methodimplicit thisobject state

Related Programs