Java Non-Access Modifiers
In this page:
What are Non-Access Modifiers?
Non-access modifiers control a class, method, or variable's behavior rather than its visibility -- keywords like static, final, and abstract change how a member works, unlike access modifiers such as public or private which control who can see it.
Example: What are Non-Access Modifiers?
class Circle {
static final double PI = 3.14159; // static and final change behavior, not visibility
}
public class Main {
public static void main(String[] args) {
System.out.println(Circle.PI);
}
}
Login to try C/C++/Java/PHP code in the editor
The static Modifier
The static modifier attaches a field or method to the class itself rather than to individual objects, so a static field is shared by all instances and a static method can be called without creating an object first.
Example: The static Modifier
class Counter {
static int count = 0;
static void increment() {
count++;
}
}
public class Main {
public static void main(String[] args) {
Counter.increment();
Counter.increment();
System.out.println(Counter.count);
}
}
Login to try C/C++/Java/PHP code in the editor
The final Modifier
The final modifier prevents further change: a final variable can only be assigned once, a final method cannot be overridden by a subclass, and a final class cannot be extended by any other class.
Example: The final Modifier
final class Constants {
}
public class Main {
public static void main(String[] args) {
final int max = 100;
// max = 200; // would not compile
System.out.println(max);
}
}
Login to try C/C++/Java/PHP code in the editor
The abstract Modifier
The abstract modifier marks a class as unable to be instantiated directly and marks a method as having no body, requiring every concrete subclass to provide its own implementation of that method.
Example: The abstract Modifier
abstract class Shape {
abstract double area();
}
class Square extends Shape {
double side = 4;
double area() {
return side * side;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Square().area());
}
}
Login to try C/C++/Java/PHP code in the editor
Combining Non-Access Modifiers
Non-access modifiers can be combined on the same member when their meanings don't conflict, such as static final for a shared, unchangeable constant, or abstract and static appearing together in different contexts within an abstract class.
Example: Combining Non-Access Modifiers
class Config {
static final int MAX_USERS = 100; // static + final together
}
public class Main {
public static void main(String[] args) {
System.out.println(Config.MAX_USERS);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: