In this section, we will learn more about modifiers.
Modifiers provide additional functionality to attributes, methods and classes.
Some modifiers we will be taking a look are static and final modifiers.
The static Modifier
The static modifier makes an attribute or a method belong to a class, rather than an object.
As an example, consider this class:
class Math {
final static E = 2.718281828459045;
static int sqr(int x) {
return x * x;
}
static long sqr(long x) {
return x * x;
}
}What this means is that instead of creating a new object to access them, we can instead reference the class to access them.
class Math {
final static double E = 2.718281828459045;
static int sqr(int x) {
return x * x;
}
static long sqr(long x) {
return x * x;
}
}
class Main {
public static void main (String[] args) {
System.out.println(Math.E);
}
}In the same way as methods, we can call a static method from a class by referencing the class instead of the object.
class Math {
final static double E = 2.718281828459045;
static int sqr(int x) {
return x * x;
}
static long sqr(long x) {
return x * x;
}
}
class Main {
public static void main (String[] args) {
int number = 7;
System.out.println(number + " squared is equal to " + Math.sqr(number));
}
}This can be very beneficial when you are simply making packages, which will be covered in the next section.
The final Modifier
The final modifier makes attributes and methods immutable and fixed.
In the example from before, we set the attribute E into a final attribute, this means that changing its value will result in an error.
class Math {
final static double E = 2.718281828459045;
static int sqr(int x) {
return x * x;
}
static long sqr(long x) {
return x * x;
}
}
class Main {
public static void main (String[] args) {
Math.E = 3; // Error: E in class Math is final
System.out.println(Math.E);
}
}This is equivalent to using final when declaring variables that does not need to be changes.