0/30 Days Completed 0 Learning Days
Day 26 of 30 · Week 4 — OOPs Through Java
Access modifiers
1 Learn
Access modifiers control who can see a class member.
public — everywhere. private — only inside the same class. protected — same package, plus subclasses in other packages. default (no keyword) — only inside the same package.
A good habit: keep fields private and expose only the methods others need.
2 See the Code
Java
class Locker {
public String owner = "Ananya";
protected int size = 2;
int floor = 1; // default (package) access
private String pin = "4321";
private boolean check(String p) { return pin.equals(p); }
public void open(String p) {
System.out.println(check(p) ? "Opened" : "Wrong PIN");
}
}
public class Hostel {
public static void main(String[] args) {
Locker l = new Locker();
System.out.println(l.owner);
l.open("1111");
l.open("4321");
// l.pin -> compile error: pin is private
}
}- owner is public, so main can read it.
- pin and check() are private, used only inside Locker.
- open() is the public way in.
Output
Ananya Wrong PIN Opened
3 Practice
- Draw a table of the four modifiers and tick where each is visible: same class, same package, subclass, everywhere.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. A member with no modifier is visible...
2. Most restrictive modifier?
Step 5
Answer and check the Quick Check above to unlock this.