The static and final keywords are two important modifiers in Java that have different purposes and effects. Here is a brief summary of their differences:
- The static keyword is used to indicate that a variable, method, block, or nested class belongs to the class, not to any instance of the class. This means that only one copy of the static member exists in the memory, regardless of how many objects of the class are created. Static members can be accessed directly by using the class name, without creating an object. For example:
class Math {
// static variable
public static final double PI = 3.14159;
// static method
public static int add(int a, int b) {
return a + b;
}
}
// access static members without creating an object
System.out.println(Math.PI); // prints 3.14159
System.out.println(Math.add(2, 3)); // prints 5
- The final keyword is used to declare a constant variable, a method that cannot be overridden, or a class that cannot be inherited. This means that the value of a final variable cannot be changed once assigned, the implementation of a final method cannot be changed by a subclass, and the functionality of a final class cannot be extended by a subclass. Final members can provide security and performance benefits. For example:
// final variable
final int x = 10;
x = x + 1; // error: cannot assign a value to final variable x
// final method
class A {
public final void show() {
System.out.println("This is a final method");
}
}
class B extends A {
public void show() { // error: show() in B cannot override show() in A
System.out.println("This is an overridden method");
}
}
// final class
final class C {
// some code
}
class D extends C { // error: cannot inherit from final C
// some code
}