On Day 19, we learn about access modifiers. Access modifiers in Java determine the visibility and accessibility of classes, fields, and methods. The four main access modifiers are public, private, protected, and default (no keyword).
1. public
A public
member can be accessed from anywhere in the program.
class Student {
public String name;
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Alice"; // accessible
System.out.println(s.name);
}
}
Explanation: Since name
is public, it can be accessed directly outside the class.
2. private
A private
member can only be accessed within the same class.
class Student {
private int age;
void setAge(int a) {
age = a;
}
int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
// s.age = 20; ❌ error: age has private access
s.setAge(20);
System.out.println(s.getAge());
}
}
Explanation: private
fields are hidden and can only be accessed through methods (getters/setters).
3. protected
A protected
member can be accessed within the same package and by subclasses (even in different packages).
class Person {
protected String name;
}
class Student extends Person {
void display() {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Bob"; // accessible in subclass
s.display();
}
}
Explanation: protected
is more open than private
but not as open as public
.
4. default (no modifier)
If no modifier is specified, it is considered default. Default members are accessible only within the same package.
class Student {
String course; // default access
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.course = "Java"; // works if in same package
System.out.println(s.course);
}
}
Explanation: Default access is package-private, meaning the field/method/class can only be used inside the same package.
Summary
- public – accessible from anywhere.
- private – accessible only within the class.
- protected – accessible in the same package and subclasses.
- default – accessible only in the same package.