Java methods are equivalent to C++ functions. Objects can communicate with each other using methods. Java’s methods can be classified in the two categories:
Just like static variables and instance variables, there are static methods and instance methods.
1. Instance Methods
The general form of an instance method is:
<return-type> <method-name> (parameter-list)
{
<method-body>
}
Method definition has four parts:
- Instance Methods
- Static Methods
Just like static variables and instance variables, there are static methods and instance methods.
1. Instance Methods
The general form of an instance method is:
<return-type> <method-name> (parameter-list)
{
<method-body>
}
Method definition has four parts:
- Name
- Return Type
- List of Parameters
- Method Body
The return type can be a primitive data type or reference data type. In case, the method returns a
reference, the return type will be the name of the class to which the object referred to by the returned reference belongs. It is must to declare the return type even if the method does not return any value. In this case, the return type should be declared as void.
The method’s formal parameters/arguments are specified within the parenthesis after the method name. The syntax is same as in C/C++.
The method body may contain any valid Java statement. If the method has a return type, then a value must be returned through return statement.
Invoking/Calling Instance Methods
The dot (.) operator is used to invoke/call the instance methods. The general form for calling the
instance methods using the dot operator is:
<object-reference>.<method-name>(paremeter-list)
Where <object-reference> is some reference variable pointing to an object and <method- name> is the name of an instance method. For example, after creating an object of type Box and storing its reference in the reference variable b1, we can call the instance method volume() using dot operator as follows:
Box b1 = new Box();
b1.volume();
Instance methods can access the instance variables as well as static variables.
Example: The following program demonstrates how to call a instance method.
1 class Box
2 { double width; //instance variables
3 double height;
4 double depth;
5 void volume() //instance method
6 { System.out.println("volume is:" + width * height * depth);
7 }
8 }
1 class BoxDemo_4
2 { public static void main(String args[])
3 { Box b = new Box();
4 b.width = 10;
5 b.height = 20;
6 b.depth = 15;
7 b.volume();
8 }
9 }
In the main() method an instance of the class Box is created, its instance variables are initialized and then the instanced method is called. The instance method volume() calculates and displays the volume of the Box.
While accessing an instance variable inside main() method, we have used object reference. It is required, as we can not access an instance variable directly inside a static method. However, when an instance variable is accessed by a method that is defined in the same class as the instance variable, the instance variable can be referred directly.
In fact we cannot specify the object reference in the method volume(), in the above example. This is due to the fact that unlike instance variables, there is only one copy of the instance methods. The instance methods use the copy of the instance variables of the object through which they are called. So the same method called through different object references will use different copy of the instance variables and hence the name instance method.
Implicitly an instance variable referred directly in a method uses this reference. For example, in the above program the direct reference to variables width, height and length is equivalent to this.width, this.height and this.length. The reference this inside a method refers to the current object (i.e. the object on which the method is called). The reference this is replaced by the reference of the invoking object at run-time. Hence the same instance method invoked through different objects will use different set of instance variables and hence will normally give different results.
Example: The following program demonstrates that calling non-static/instance method on different objects results in different output.
1 class Box
2 { double width; //instance variables
3 double height;
4 double depth;
5 void volume() //instance method
6 { System.out.println("volume is "+width*height*depth);
7 }
8 }
1 class BoxDemo4
2 { public static void main(String args[])
3 { Box b1 = new Box();
4 Box b2 = new Box();
5 b1.width = 10; b1.height = 20; b1.depth = 15;
6 b2.width = 3; b2.height = 6; b2.depth = 9;
7 b1.volume();
8 b2.volume();
9 }
10 }
The first call to method volume() displays the volume of the box b1 correctly as 6000 and the
second call to method volume() displays the volume of the box b2 as 162.
Method Returning a value
Example: The following program demonstrates use of method, which returns a value i.e. its
return type, is not void.
1 class Box
2 { double width;
3 double height;
4 double depth;
5 double volume()
6 { return width * height * depth;
7 }
8 }
1 class BoxDemo5
2 { public static void main(String args[])
3 { Box b1 = new Box();
4 Box b2 = new Box();
5 double vol;
6 b1.width = 10;
7 b1.height = 20;
8 b1.depth = 15;
9
10 b2.width = 3;
11 b2.height = 6;
12 b2.depth = 9;
13 vol = b1.volume();
14 System.out.println("Volume is : " + vol);
15 vol = b2.volume();
16 System.out.println("Volume is : " + vol);
17 }
18 }
Passing Arguments to Methods.
In the previous examples using class BoxDemo5, we initialized the instance variables directly to
keep the things simple. This should not be done as it defeats the purpose of data encapsulation.
Moreover the instance variables can be made private so that they cannot be accessed from other
classes. In that case it would not be possible to access the instance variables directly. The only
alternative in that case is to define a method that takes width, height, and length as arguments
and then initializes the instance variables.
Example: The following program defines two classes: Box and BoxDemo6. The class Box has a
method that takes arguments. The classes may be defined in same source file or in two different
source files. But in both the cases you will get two classes after compilation: Box.class and
BoxDemo6.class. You can execute only class BoxDemo6.class as only this class has main()
method. It also makes use of class Box for creating an instance/object and calling methods.
1. class Box
2. { private double width, height, depth; //data hiding
3. double volume()
4. { double vol = width * height * depth;
5. return vol;
6. }
7. void setDimensions(double w, double h, double d)
8. { width = w;
9. height = h;
10. depth = d;
11. }
12. /* Instance Variable Hiding
13. void setDimensions(double width,double height,double depth)
14. { width = width;
15. height = height;
16. depth = depth;
17. }
18. */
19. /* Instance Variable Hiding
20. void setDimensions(double width,double height,double depth)
21. { this.width = width;
22. this.height = height;
23. this.depth = depth;
24. }
25. */
26. }
1 class BoxDemo6
2 { public static void main(String args[])
3 { Box b1 = new Box();
4 Box b2 = new Box();
5 b1.setDimensions(10, 20, 30);
6 double volume = b1.volume();
7 System.out.println(volume);
8 b2.setDimensions(5, 10, 15);
9 volume = b2.volume();
10 System.out.println(volume);
11 }
12 }
You cannot access the instance variables of class Box though object reference in the class
BoxDemo6 as instance variables are declared private. The private instance variables can be
accessed only in the class in which they are declared.
Nesting of Instance Methods
One instance method can invoke the other instance method of the same class without qualifying
i.e. by just specifying the method name. For example, in the following program, calCost()
method, which is an instance method, can call the instance method area() of the same class
simply by its name.
1 class Circle
2 { static final float PI = 3.1415f;
3 float puCost; // say cost of painting unit area
4 float radius;
5 float area()
6 { return PI * radius * radius;
7 }
8 float calCost()
9 {
10 float cost = puCost * area();
11 return cost;
12 }
13 public static void main(String args[])
14 { Circle circle = new Circle();
15 circle.puCost = 100;
16 circle.radius = 3;
17 float area = circle.calCost();
18 System.out.println(area);
19 }
20 }
2. static Methods
The static methods can be accessed like static variables through the class name without creating
any instance/object. The static methods can also be called using the object reference. The static
methods can directly access only static variables irrespective of the fact that they are invoked
through class name or object reference.
The general form of a static method is:
static <return-type> <method-name> (parameter-list)
{
<method-body>
}
The general form is same as that of a instance method with the only difference that the modifier
static is used before the return type.
Invoking/Calling static Methods
Example: The following program demonstrates the use of static method. The method area()
takes one argument representing the radius of the circle and calculates its area. The method area() does not use any instance variable so it is declared as static and can be invoked through class name without creating any instance/object.
1 class Circle
2 { static final float PI = 3.1415f;
3 static float area(float radius)
4 { return PI * radius * radius;
5 }
6 public static void main(String args[])
7 { int r = 4;
8 float area = Circle.area(r);
9 //float area = area(r); //Nesting of static methods
10 System.out.println("Area: "+area);
11 }
12 }
Here the static variable PI is declared to be constant by putting modifier before the type. This is
equivalent to const of C/C++.
Nesting of Class Methods
One class method can invoke the other class method of the same class without qualifying i.e. by
just specifying the method name. For example, in the above program main() method, which is
static can call the static method area() of the same class simply by its name:
float area = area(r);
This nesting can go to any depth.