Introduce Java Modifiers and give examples
In Java, modifiers are keywords that you can use to change the way classes, methods, and variables behave. They can be broadly categorized into two types: access modifiers and non-access modifiers.
Access modifiers control the visibility of classes, methods, and variables. There are four main access modifiers in Java:
class Example {
public int publicVar; // Accessible from anywhere
protected int protectedVar; // Accessible within the package and subclasses
int defaultVar; // Accessible only within the package
private int privateVar; // Accessible only within this class
public void display() {
System.out.println("Public: " + publicVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Default: " + defaultVar);
System.out.println("Private: " + privateVar);
}
}
Non-access modifiers provide additional functionality to classes, methods, and variables. Some common non-access modifiers include:
class NonAccessModifiersExample {
static int staticVar = 0; // Belongs to the class
final int finalVar; // Cannot be changed once initialized
// Constructor to initialize final variable
NonAccessModifiersExample(int value) {
this.finalVar = value;
}
static void staticMethod() {
System.out.println("Static method called. Static variable: " + staticVar);
}
final void finalMethod() {
System.out.println("This is a final method.");
}
}
// Abstract class example
abstract class AbstractClass {
abstract void abstractMethod(); // Must be implemented by subclasses
}
// Subclass implementing the abstract method
class ConcreteClass extends AbstractClass {
void abstractMethod() {
System.out.println("Abstract method implemented.");
}
}
Modifiers in Java are essential for controlling access and behavior of classes, methods, and variables. Understanding how to use them effectively is crucial for writing robust and maintainable Java code.