Introduction
In this lesson, we will explore the final and static keywords in Java, essential components of the language's object-oriented programming (OOP) architecture. You will understand how these keywords modify the behavior of classes, methods, and variables, and when it's appropriate to use them in your coding practices. Additionally, we will delve into practical coding examples to illustrate their functionalities in real-world applications.
The Purpose of the Final Keyword in Java
The final keyword in Java is used to restrict the user from modifying a variable, method, or class. Once declared as final, the following rules apply:
- A final variable cannot be reassigned after its initial assignment.
- A final method cannot be overridden in subclasses.
- A final class cannot be subclassed.
Final Variables
A final variable is a constant that holds a value which cannot be changed once assigned. Here’s an example:
public class FinalExample {
final int CONSTANT_VALUE = 100;
public void tryToChangeValue() {
// Uncommenting the line below will cause a compilation error
// CONSTANT_VALUE = 200;
}
}
Output:
// Compilation Error: cannot assign a value to final variable CONSTANT_VALUE
Final Methods
When a method is declared as final, you prevent any subclasses from overriding it, preserving its original implementation. For example:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// This will cause a compilation error if uncommented
// void display() {
// System.out.println("Overriding final method");
// }
}
Output:
// Compilation Error: cannot override display() in Child
Final Classes
A final class cannot be subclassed, making it immutable in terms of its structure. Here's an example:
final class FinalClass {
void show() {
System.out.println("Cannot inherit this class.");
}
}
// Uncommenting the line below will cause a compilation error
// class ExtendedClass extends FinalClass {}
The Static Keyword for Class-Level Members
The static keyword in Java denotes that the particular member belongs to the class itself rather than any instance of the class. It can be applied to variables, methods, and blocks.
Static Variables
Static variables are shared among all instances of a class, as they belong to the class itself. Here's an example:
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println("Count: " + count);
}
}
public class TestStatic {
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Static Methods
Static methods can be called without creating an instance of the class and can only access static variables and methods. Seen below:
class StaticDemo {
static void staticMethod() {
System.out.println("Static method called.");
}
}
public class TestStaticMethod {
public static void main(String[] args) {
StaticDemo.staticMethod(); // Call without instance
}
}
Output:
Static method called.
Using Final and Static Together
Combining both keywords can be useful. A static final variable typically represents a constant value that remains unchanged across instances and belongs to the class itself. Here’s an example:
class Constants {
static final double PI = 3.14159;
}
public class TestConstants {
public static void main(String[] args) {
System.out.println("Value of PI: " + Constants.PI);
}
}
Output:
Value of PI: 3.14159
Practical Coding Example: Creating a Static Final Class
Let’s illustrate the use of static final by creating a utility class that contains constants and static methods:
class MathUtils {
static final double SQUAREROOT_2 = 1.414;
static double square(double number) {
return number * number;
}
}
public class TestMathUtils {
public static void main(String[] args) {
System.out.println("Square of 4: " + MathUtils.square(4));
System.out.println("Square root of 2: " + MathUtils.SQUAREROOT_2);
}
}
Output:
Square of 4: 16.0
Square root of 2: 1.414
Summary / Key Takeaways
In this lesson on Final and Static Keywords Explained, you have learned:
- Final Variables are immutable after initialization, ensuring constant values throughout the program.
- Final Methods prevent method overriding, maintaining the integrity of a class's functionality.
- Final Classes cannot be subclassed to preserve their definition and implementation.
- Static Members belong to the class rather than instances, allowing shared values across different objects.
- Static Final variables provide a way to create constants accessible via the class.
- Understanding when to use final and static is crucial for effective OOP design in Java.
- Combining final and static enhances code clarity and prevents unintended modifications.
- Practical examples illustrate the real-world applications and benefits of these keywords.