Java Modifiers
Modifiers add rules to Java declarations. Some control where a class or member can be accessed. Others describe properties such as belonging to the class or preventing reassignment.
Why Do We Need This?
A score field may need to be private so changes go through a method. A shared constant can be static and final so it belongs to the class and cannot be assigned another value.
Main Ideas
| Concept | What it means |
|---|---|
| Access modifiers | public, protected, and private control access |
| Package-private access | Applies to ordinary class members with no access modifier |
| static | Makes a field or method belong to the class |
| final | Prevents reassignment of a variable; has different rules for classes and methods |
| abstract | Describes a class that cannot be instantiated or a method without an implementation |
Simple Working Example
Run this program on its own. All required imports and classes are included.
class Quiz {
private int score = 8;
public static final int MAX_SCORE = 10;
public int getScore() {
return score;
}
}
public class HelloWorld {
public static void main(String[] args) {
Quiz quiz = new Quiz();
System.out.println(quiz.getScore() + " out of " + Quiz.MAX_SCORE);
}
}Output
8 out of 10The private score is read through getScore(). MAX_SCORE belongs to Quiz because it is static, and final prevents assigning a new value to it.
Topics in This Section
Easy Way to Remember
Access modifiers answer where code may be used. Non-access modifiers add other rules. The default keyword is not a package-private access modifier.
See you in next page....??