Java Modifiers
Modifiers are keywords that change how a class, field, or method can be used. Access modifiers control which code can reach a field or method.
A public field can be read
The name field carries the public modifier. Code in main reads the field through the object, and the name prints.
class Person {
public String name = "Ada";
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);
}
}A private field is refused outside its class
The name field carries the private modifier. The read in main sits outside the Person class, and the compiler refuses the line.
class Person {
private String name = "Ada";
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);
}
}A static field is shared by all objects
Each Counter creation adds 1 to the same count field. Two objects raise the shared count to 2.
class Counter {
static int count = 0;
Counter() {
count = count + 1;
}
}
public class Main {
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter();
System.out.println(Counter.count);
}
}Example
class Counter {
static int count = 0;
Counter() {
count = count + 1;
}
}
public class Main {
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter();
Counter third = new Counter();
System.out.println(Counter.count);
}
}Key points
- public marks a field that any code can reach.
- private marks a field that only its own class can reach.
- static marks a field that the class shares across all objects.
- final marks a value that cannot change after it is set.
- protected marks a field that its class and child classes can reach.
In this example, the Counter class holds one static count field. Each creation runs the constructor and adds 1 to the one shared field. The print reads the field through the class name and shows 3.
Note
The access modifier stands before the type of the field.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does the private modifier do to a field?