OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 15 : Nesting of Methods in Java

 

Unit - 2

Topic - 15 : Nesting of Methods in Java

In Java, normally a method of a class is called using an object of that class with the dot (.) operator.
However, if one method of a class calls another method from the same class, we don’t need to use an object — we can call it directly by name.
This concept is called Nesting of Methods.


Example Program

// Program to demonstrate Nesting of Methods class Test { int a, b; // Constructor Test(int p, int q) { a = p; b = q; } // Method to find the greatest of two numbers int greatest() { if (a >= b) return a; else return b; } // Method that calls another method (nested call) void display() { int great = greatest(); // Calling greatest() without object System.out.println("The Greatest Value = " + great); } } class Temp { public static void main(String args[]) { Test t1 = new Test(25, 24); // Create object t1.display(); // Call display(), which internally calls greatest() } }

Output

The Greatest Value = 25

Explanation

  • The method display() calls greatest() directly (without using an object).

  • Both methods belong to the same class (Test), so we can use the method name directly.

  • This avoids repetitive object references when calling methods inside the same class.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies