Course Content‎ > ‎Session 4‎ > ‎Objects and Classes‎ > ‎

Methods (Advanced)

An object requires to interact with other objects. How a method is defined, declared, parameters are passed and value is 
returned by the method has been explained in detail earlier. Let’s continue with the advanced information about methods.
Nesting of Methods
A method of a class can be called by an object of that class, using the dot operator.  But there is an exception to this. A method can be called by another method of the same class by using the name of that method. This is called as nesting of 
methods. Given below is an example, which will explain the nesting of methods:
    class Nesting
        int m, n;  
        // constructor, to initialize the instance variables 
        Nesting(int x, int y) 
            m = x;  
            n = y;
        /* largest is a member function, to find which of the two instance 
           variables m or n is largest */
        int largest( )
            // if m is larger than n then return m otherwise return n  
            if (m > n)  
                return m; 
                return n; 
        // this function displays the instance variable which has a larger value  
        void display( )
            // function largest is called here and value returned is assigned to large
            int large = largest( );  
            // larger value is displayed
            System.out.println("Largest number =" + large);
    } // end of the definition of class Nesting
    class NestingTest
        public static void main(String args[])  
            /* object nest is constructed and 50 and 40 are two values passed
               to be assigned to instance variables m and n  */ 
            Nesting nest = new Nesting(50, 40);
            /* display method is called */
The program given above shows the nesting of methods inside a class. The class Nesting defines one constructor and two methods. These two methods are: largest() and display().  The method display() calls the method largest() to determine the largest of the two numbers and then displays the result. A method can call any number of methods. It is also possible for a called method to call another method. 
Calling a Method in Java
In the example given above, findLargest method is called from the main() method. The statement given below calls the findLargest method from the main() method.
    Largest = L1.findLargest(num1, num2, num3, num4);

To call a particular method, object of the class in which that method is stored has to be used to call that method. The syntax for calling a method in Java is:
objectName is the name of the object of the class in which the method is defined.
methodName is the name of the method that has to be called.