Nesting of methods
We have elaborated earlier that a method of a class can be called only by an object of that class or class itself, in the case of static methods ) using the dot operator.
A method can be called by using only its name by another method of the same class. This is known as nesting of methods.
Program illustration of nesting of methods
In program the class nesting defines one constructor and two methods namely largest() and display(). The method display() calls the method largest () to determine the largest of the two numbers and then display the results.
Class nesting
{
Intm ,n;
Nesting(int x , int y ) // constructor method
{
M = x;
N = y;
}
Int largest ()
{
It(m>+n)
Return(m);
Else
Retrun(n);
}
Void display( )
{
Int large = largest (); //calling a method
System.out.println(“Largest value “ + large);
}
}
Class nestingtest
{
Public static void main(string args[])
{
Nesting nest = new nesting( 50,40);
Nest.display();
}
}
Output
Largest value = 50 ;
Note : A method can call any number of methods. It is also possible for a called method to call another method. That is method 1 may call method 2 and which inreturn may call method 3 .