Nesting of methods

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 .

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control