Static & Final Keywords
Understand static members, final variables, and their crucial role in Java programming.
Understand static members, final variables, and their crucial role in Java programming. This hands-on tutorial focuses on practical implementation of static & final keywords concepts.
Static & Final Keywords
The static Keyword
static means the member belongs to the class rather than to any specific instance.
Static Variables
Shared across all instances of the class.
class Counter {
static int count = 0; // Shared by all Counter objects
Counter() {
count++;
}
}
Static Methods
Can be called without creating an object.
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
// Usage
int result = MathUtils.add(5, 3); // No object needed!
Static Blocks
Executed once when the class is loaded.
class Database {
static {
System.out.println("Database driver loaded");
}
}
[!IMPORTANT] Static methods cannot access instance variables or call instance methods directly!
The final Keyword
final means "cannot be changed."
Final Variables (Constants)
final double PI = 3.14159;
// PI = 3.14; // ERROR! Cannot reassign
Final Methods
Cannot be overridden by subclasses.
class Parent {
final void display() {
System.out.println("Cannot override me!");
}
}
Final Classes
Cannot be inherited.
final class Utility {
// No one can extend this class
}
Combining static and final
class Constants {
public static final double PI = 3.14159;
public static final String APP_NAME = "MyApp";
}
AI Mentor
Confused about "Java static and final keywords usage and differences"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Can a static method access instance variables?