Java Instance Methods

In this post, you will learn to:

  • Explain the purpose of instance methods and its naming conventions.
  • Describe variable-argument methods.

Concept of Instance Methods

An instance method is defined as the actual implementation of an operation on an object. It specifies the steps or the manner in which the requested operation is to be carried out.

An instance method is a method that is invoked by an instance and one that can access instance variables. Following conventions have to be followed while naming a method:

  • Cannot be a Java keyword.
  • Cannot contain spaces.
  • Cannot begin with a digit.
  • Can begin with a letter, underscore or a “$” symbol.
  • Should be a verb in lowercase.
  • Should be descriptive and meaningful.
  • Should be a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns,and so forth.

The figure below shows the instance methods declared in the class, Student that are invoked by all the instances of the class.

The following is the syntax for declaring an instance method in a class.

Syntax:

<returntype> <method_name> ([list of parameters]) {
 // Body of the method
}

where,
returntype: specifies the data type of the value that is returned by the method.
method_name: is the method name
list of parameters: are the values passed to the method.

The following code demonstrates the declaration of instance methods within the class, Student.

Code Snippet:

// Class Declaration
class Student {
   // Instance variable
   int age;
   // Instance methods
   int getAge(){
     // Accessing instance variable
     return age;
   }
   void setAge(int i){
     age = i;
   }

   public static void main(String[] args)
   {
      Student stud = new Student();
      stud.age = 24;
      // Invoking the instance method through an object using dot operator
      int resultage = stud.getAge();
      System.out.println("Age of the student is:" + resultage);
   }
}

As shown in the code, Student class contains an instance variable, age and two instance methods,namely, getAge() and setAge(). The main() method creates an instance named stud for the class,Student. The instance, stud access the age variable and initializes it to 24. The instance methods can access the variables declared within the class, hence a call to getAge() method returns the value of variable age, that is further stored in a local variable, resultage.

Output:

Age of the student is: 24

Javadoc Comments for Methods

Note: The Javadoc comments that are used for methods in Java are:

/**
 * Method description: Javadoc comments on description of the method.
 * @param tag: is followed by the name (not data type) and description of
 * the parameter.
 * @return tag: is used to specify the return type of methods. It is not
 * used with methods having a void return type.
 */

Statements in the current method after the return statement are skipped, and the control returns to the statement that invoked the method. With methods that are declared void, use the form of return statement that does not return any value:

return;

Sometimes, a void method has to return explicitly depending on a condition. In this situation this form of return statement can be used. For example:

// Assumes age is an instance variable
// in a class that is already defined
void setAge(int age){
   if (age<10) return;
      this.age=age;
}

Passing Arguments by Value

Java has the capability of passing arguments by value. This means that when the value from the calling method is passed as an argument to the called method, any changes made to that passed value in the called method will not modify the value in the calling method. Variables of primitive data types, such as int and float are passed by value. This is a safe way to pass a parameter.

The following code demonstrates the passing of arguments to the called method, checkVal() using pass by value method.

Code Snippet:

public class PrimitiveDatatypeClass{

   public static void main(String[] args) {
      int i = 3; 
      //invoke checkVal() with i as argument
      checkVal(i);

      // print i to check its value
      System.out.println("After invoking checkVal, i = " + i);
   }

   // parameterized method
   // change value of parameter in checkVal()
   public static void checkVal(int j) {
      j=j+5;
   }
}

Output:

After invoking checkVal, i = 3

Passing Arguments by Reference

Call by reference enables the called method to change the value of the parameters passed to it from the calling method. Reference data type parameters are passed to the methods by value and not by reference. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the instance variables can be changed in the method.

When references are passed as parameters, the caller can change the values stored but not the reference variables. The following code demonstrates the passing of arguments to the called method, drawLine() using pass by reference method.

Code Snippet:

public void drawLine(Line line, int pointX, int pointY) {
 
   line.setX(line.getX + pointX);
   line.setY(line.getY + pointY);

   //code to assign a new reference to line
   line = new Line(0, 0);
}

The method is invoked with the necessary arguments as follows:

obj.drawLine(myLine, 3, 6);

Variable Argument Methods

Variable argument allows calling a method with variable number of arguments. This is used when the number of arguments to be passed to a method is not known at the time of writing of a method.

The figure below shows the method declaration with variable number of arguments.

The following is the syntax for declaring a method with variable number of arguments.

Syntax:

<method_name>(type ... variableName){
// method body
}

The ellipsis (…) is used to identify the variable number of arguments. The following code demonstrates the declaration of method with variable number of arguments within a class.

Code Snippet:

class Welcome {
    public static void dispNumber(int...num) {
      for (int i : num) {
         System.out.println("Model Number is " + i + ". ");
         }
     }
     public static void main(String[] args) {
        dispNumber(201, 301);
    }
}

Output:

Model Number is 201.
Model Number is 301.

The statement for (int i:num) is an enhanced form of for loop introduced in J2SE 5.0. This type of for loop representation is very useful for variable arguments. The statement allows i to iterate through list of variable arguments list, that is, num.

Related Post