The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Methods in Java

We have been talking about methods a lot in the tutorial so far. This section intends to fill up gaps (if any) in understanding of methods. Also, we introduce some additional concepts related to methods. A method in Java is simply a set of statements grouped together to perform a specific task.

Defining and Calling a method
Method Definition consists of following parts :
Modifier Header : It consists of modifiers ( access and non-access ), return type, method name and the arguments / parameters. Please note that parameters and modifiers are optional.
Modifier Body: It consists of a set of statements which perform a task.
Method Call is calling a defined method to get a task done.
Following program illustrates the concept :

class Rectangle {
   /* Method Definition
    * Modifier : public ( defines visibilty )
    * Return Type : int ( method can return int type values only )
    * Name : getArea
    * Parameters : length (int) and breadth (int)
    */
   public int getArea(int length, int breadth) {
      /* Method Body */
      int area = length * breadth;
      return area;
   }

   /* Method with no modifier specified and no parameter passed.
    * Return type: void ( doesn't return anything )
    */
   void print() {
      System.out.println("I am a rectangle");
   }

   /* static method which belongs to class */
   static void printGen() {
      System.out.println("I have four sides");
   }
}

public class MethodsTest {
   /* Method Definition
    * Modifiers : public, static ( class method )
    * Return Type : void ( doesn't return anything )
    * Name : main
    * Parameters : array of command line aruments
    */
   public static void main(String args[]) {
      Rectangle rect = new Rectangle(); // create a rectangle object
      int ar = rect.getArea(5, 7); /* calling a method with two parameters
			            * 5 is passed to length and 7 to breadth
                                    * returned value is stored in variable 'ar'
                                    */
      System.out.println("Area of the rectangle = " + ar);
      rect.print(); /* calling a void type method */
      Rectangle.printGen(); /* calling a static method using class name */
   }
}

In the above program, an important point to consider is how a function which returns a value is called and how a void type function is called. Also, note that static method is called using the class name and not using any abject.
An important aspect of method call is that the arguments to the called method is pass-by value. Suppose we have a variable x with value 6 inside a calling method ( from where the required method will be called ). If we pass this variable as an argument to a method which increments its value, then the incremented value won't be reflected in the calling method. Thus, only the values in the variable is passed and not the variable itself. Following program illustrates this behaviour :

public class PassByValueDemo {
   public static void increment(int val) {
      val++;
   }
   public static void main(String args[]) {
      int x = 6;
      System.out.println("Before Calling inrement : x = " + x);
      /* call the increment method
       * value of x is passed to val
       */
      increment(x);
      System.out.println("After Calling inrement : x = " + x);
   }
}


Method with variable no. of arguments
In Java, we can pass variable number of arguments of same data type to a method. In the method header, we specify the parameter type followed by ellipsis ( ... ) and the object which stores the passed arguments. Only one variable length parameter can be present and that must be the last parameter. Other parameters must come before the variable length parameter. Following program illustrates this concept :

public class VarArgsDemo {
   /* This method can take any no. of integer values and
    * returns the sum of those values
    */
   public static int add(int... values) {
      int sum = 0;
      for(int i = 0; i < values.length; i++) {
         sum += values[i];
      }
      return sum;
   }
   /* main() method */
   public static void main(String args[]) {
      int sum1, sum2;
      sum1 = add(3, 6); // calling add with two arguments
      sum2 = add(7, 6, 9); // calling add with three arguments
      System.out.println("Sum1 = " + sum1);
      System.out.println("Sum2 = " + sum2);
   }
}


finalize( ) Method
Java has an automatic garbage collecting system i.e it frees up all the memory resources held by an object when that object goes out of scope. But the garbage collector cannot free up non-object resources ( for e.g, suppose a file is opened and we forget to close it, then the file descriptor is not freed when the object is destroyed ). This is where finalize( ) method comes into play. We define this method to specify those tasks or actions that must be done before the object is destroyed. This method is executed automatically by the garbage collector when it determines that there are no more references to the object. The finalize( ) method must be declared as protected because it is not supposed to be accessed outside the class. One important point to note is that we cannot deterministically say when the finalize( ) method will be called. It depends on the time when garbage collector starts its operation. So if you are trying to print something inside the finalize( ), you may not see it on screen.

Method Overloading
Java provides a feature to define two or more methods with the same name but different argument list. The argument list can vary in terms of no. of arguments, data types of arguments or both. This is known as method overloading and is used when an object is expected to perform similar tasks but on different input parameters. A constructor like any other method can also be overloaded. Following program illustrates method overloading :

class Addition {
   /* add() method is overloaded */
   int add(int x, int y) { // add() with two int parameters
      return (x + y);
   }
   int add(int x, int y, int z) { // add() with three int parameters
      return (x + y + z);
   }
   String add(String x, String y) { // add() with 2 String parameters
      return (x + y);
   }
}
public class MethodOverloadDemo {
   public static void main(String args[]) {
      Addition sum = new Addition();
      int s1 = sum.add(5, 7); // call add() with 2 parameters
      int s2 = sum.add(5, 7, 13); // call add() with 3 parameters
      String s3 = sum.add("cse", "geek");
      System.out.println("s1 = " + s1);
      System.out.println("s2 = " + s2);
      System.out.println("s3 = " + s3);
   }
}

Method overloading is a means to implement static / compile time polymorphism. In the above program, depending on the no. and type of input parameters, appropriate add( ) method is invoked.

Method Overriding
Method overriding is a concept related to inheritance. You can skip this for now and come back after understanding inheritance but it is recommended to go through this once as it is really simple concept and the explanation given here is good enough to understand.
Let's see an example to understand the overriding concept.

Program showing basic InheritanceExplanation
class A {
   public void display() {
      System.out.println("Base(A) :: display");
   }
}

/* class B inherites or derives from class A
 * So, display() is a part of class B also.
 */
class B extends A {
   public void print() {
      System.out.println("Derived(B) :: print");
   }
}

public class BasicInheritance {
   public static void main(String args[]) {
      A obj_a = new A();
      B obj_b = new B();
      obj_a.display();
      obj_b.print();
      obj_b.display(); // display() belongs to B also
   }
}
A is the base / parent class and B is the derived / child class which inherits from A. Thus, the display( ) method of A becomes a part of B and can be accessed using an object of class B.
Program showing Method OverridingExplanation
class A {
   public void display() {
      System.out.println("Base(A) :: display");
   }
}

class B extends A {
   public void print() {
      System.out.println("Derived(B) :: print");
   }
   /* This method overrides the display() of class A */
   public void display() {
      System.out.println("Derived(B) :: display");
   }
}

public class OverrideDemo {
   public static void main(String args[]) {
      A obj_a1 = new A();
      A obj_a2 = new B(); // perfectly valid
      B obj_b = new B();
      obj_a1.display(); // display() of class A called
      obj_a2.display(); // display() of class B called
      obj_b.display();  // display() of class B called
   }
}
In this program, we define display( ) method inside class B. Now, which version ( base class or derived class ) of the method will be invoked when an object of class B calls display( ) ? The derived class ( B ) method overrides the base class ( A ) method i.e display( ) of B will be invoked. This is method overriding.

Note :- Constructors cannot be overridden.
           Static and Final methods cannot be overridden.
           Method Overriding implements runtime polymorphism in Java.
           private methods cannot be overridden since they cannot be inherited.

Back | Next