Nesting of Methods in Java


This program demonstrates nested methods in Java.

  • The demo class has two private integer variables m and n and a constructor that initializes these variables with the values passed as arguments. The class also has a method largest() that compares the values of m and n and returns the larger value.
  • The display() method is a nested method inside the demo class. This method calls the largest() method and assigns the returned value to a variable called large. It then prints the value of large.
  • The main() method creates an instance of the demo class with the values 10 and 20. It then calls the display() method of the instance, which in turn calls the largest() method and prints the result.

Source Code

//Nesting of Methods in Java
class demo {
    private int m, n;
 
    demo(int x, int y) {
        m = x;
        n = y;
    }
 
    int largest() {
        if (m > n)
            return m;
        else
            return n;
    }
 
    void display()
    {
        int large=largest();
        System.out.println("The Greatest Number is : "+large);
    }
 
}
public class nested_method {
    public static void main(String args[]) {
        demo o =new demo(10,20);
        o.display();
    }
 
}
 

Output

The Greatest Number is : 20
To download raw file Click Here

Basic Programs