What is static?
static
members (variables and methods) are properties of a class rather than of each object
. Thus, you don’t need to create an object
to access a static
variable or call a static
method
They are also called class variables
and class methods
.
static
methods can only access static
variables.
Typically, static
methods operate on the parameters passed.
Example of a class method
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ArrayService {
/**
* @param data
* @return true if array is in ascending order, false otherwise
public static boolean isAscending(int[] data) {
for(int i=0; i < data.length - 1; i++) { //go only to second last item
if(data[i] > data[i+1]) { //violation to ascending order
return false;
}
}//end of loop means no violations
return true;
}
}
The method isAscending
is labelled as static
. This means, it can be called directly on the class.
1
2
3
4
5
6
7
public class Client {
public static void main(String[] args) {
int[] a = {1, 7, 2, 9};
boolean status = ArrayService.isAscending(a);
//class method isAscending called directly on class, operates on array passed
}
}
Example of an instance method
On the other hand, instance methods operate on objects or instances of a class.
!!! We will cover this in the subsequent lecture !!!
1
2
3
4
5
6
7
public class Rectangle {
public double length, breadth;
public double area() {
return length * breadth;
}
}
1
2
3
4
5
6
7
8
9
public class Client {
public static void main(String[] args) {
Rectangle r = new Rectangle(); //instance of class created
r.length = 4; //instance variables set
r.breadth = 6;
int val = r.area();
//instance method area called on object, has knowledge of instance variables
}
}