4.7 Instance and Static Methods in Java

As well as instance and static variables, we can also have instance and static (or class) methods. By default, all methods are instance methods. Instance methods are invoked by prefixing the method with an object. For example, we invoke the instance method deposit

fredsAccount.deposit(100);

The deposit method modifies the instance variables corresponding to the fredsAccount object only.

A static method does not operate on an object. Typically, a method that performs a general- purpose calculation is a candidate for a static method. For example, we will take the Circle application from Chapter 2 and rewrite it as a class containing the calculate Area static method. This returns the area of the circle given a radius as a supplied argument.


Circle

public class Circle
{
static final double PI = 3.14159;

public static double calculateArea (double radius)
{
// area formula
return PI * (radius * radius);
}
}


Static methods, like static variables, are identified by the use of the static keyword (line 4). We can invoke the calculateArea method from any class by prefixing the method with its class name, for example

double circleArea = Circle.calculateArea(5);

An instance of the Circle class does not need to exist in order to access the calculateArea static method.

Note that though instance methods can access static variables, static methods cannot access instance variables. An attempt by a static method to access an instance variable will cause a compilation error.

No comments:

Post a Comment