Unit 2 begins:
who can see what?
Unit 1 taught you to BUILD the box. From today, Java decides who may OPEN it. Four small keywords — private, (nothing), protected, public — control every field and method's visibility across an entire codebase. Master the four circles of trust and two exam questions solve themselves on the spot.
PART F OPENS · CLASSES 13–14 · THE SKY BLOCK
One box, two classes:
first who sees it, then who may touch it.
Every Part of this course is one colour and one obsession. Part F (sky) is obsessed with a single idea: a class's inside is not public property. Class 13 gives you the four visibility keywords; Class 14 uses them to build encapsulation — the fourth pillar Unit 1 kept hinting at.
Four keywords, four circles of trust. Who can READ organizerContact? Who can CALL register()? Today you learn to answer instantly, for any member, from any file.
The payoff. Hide the state with private, guard every change with validated methods — and a canteen-card balance becomes physically impossible to over-spend.
Class 13's running example: the code behind a college fest's event app. Many teammates, many files, one question everywhere — who may see what?
Class 14's running example: the campus canteen's prepaid card. Its one sacred invariant — the balance can never go negative — needs today's keywords to survive.
Why this order? You cannot hide anything before you know the hiding keywords. So modifiers first (today), encapsulation second (C14) — and when Class 16 builds real packages, today's mysterious "default" level suddenly grows teeth. Lab 3 then makes you feel that boundary with your own hands.
CLASS 13 · THE MAP OF TODAY
Who can see what,
across a whole Java codebase.
Imagine the fest team: six students, one shared project, everybody editing everybody's classes. Without visibility rules, anyone can quietly rewrite anyone's data. Today Java hands you the rulebook.
AFTER TODAY YOU CAN…
- explainall four access levels —
private, default,protected,public— each in one exam-ready line with its use case. - classifyany member of a real class into the modifier its intended visibility demands (Activity 1 does exactly this with six CampusEventApp members).
- writea complete runnable program whose modifiers demonstrably control visibility — PYQ P1·Q12b's exact ask, solved on a sheet today.
- debugthe classic
has private accesscompile error — read it, name the cause, choose the right fix (Activity 2's fill-in-code).
WHERE THIS CONNECTS
TODAY'S WALK — IN ORDER
- The four access levels — one picture, four circles of trust
private— class-only, the diary rule- default (no keyword) — package-private, the hostel-floor rule
protected— package + subclasses, the family keypublic— everywhere, the notice board- The full visibility matrix — photograph-this table
- Worked example —
CampusEventAppwith mixed modifiers, walked member by member - Discuss access specifiers in detail PYQ P2·Q11a · 4M
- Program showing modifiers controlling visibility PYQ P1·Q12b · 4M
- Activity 1 — classify six CampusEventApp members
- Activity 2 — fill in
UserProfile's missing modifiers
CLASS 13 OF 60 · 12 CORE-TAUGHT PAGES + 0 SELF-STUDY · FEEDS LAB 3
default package — no package line at the top. Today's programs stay there on purpose: all four modifiers are fully demonstrable inside it. The cross-package drama (default access refusing entry to outsiders) needs Class 16's package statement — a forward note marks the exact spot.
PART 4 · FOUR KEYWORDS, FOUR CIRCLES OF TRUST
Your phone already knows
this entire lesson.
Think about your own phone. The lock-screen PIN — only you. The hostel floor's shared speaker — anyone on the floor. The family OTT password — the floor plus your sibling in another city. Your Insta handle — literally everyone. Java gives a class the exact same four circles, one keyword each:
Read it inside-out: each keyword UNLOCKS one more ring. private < default < protected < public — memorise the order, half the matrix is already yours.
Visible ONLY inside the class that declares it. Not to subclasses, not to neighbours — nobody. The default choice for fields.
Write NO keyword and the member is package-private: every class in the same package sees it; everyone outside is refused.
Everything default gives, PLUS every subclass — even one living in a different package. Built for the extends family channel.
Visible from every class in every package, forever. The right choice ONLY for the members you intend the world to call.
Question papers say "access specifiers"; the Java Language Specification says "access modifiers". They are two names for these exact four levels — write either in the exam, define all four, and the marks are identical. (P2·Q11a, solved later today, does exactly this.)
PART 5 · PRIVATE — THE INNERMOST CIRCLE
private: only the class
that wrote it down.
Your Insta password lives in your head and nowhere else. Even your best friend logging your account gets the password FROM you — through an action you control — never by reading your mind. That is private: the member exists, works hard, but is untouchable from outside its own class.
TWO MICRO-STORIES FIRST — SAME KEYWORD, OPPOSITE ENDINGS (RULE: MICROS BEFORE THE MAIN FILE)
NOW THE REAL FILE — WATCH THE COMPILER SAY NO, THEN YES
InstaAccountholdsprivate String password- Its own method
login()uses the password — must work mainfirst tries to readacc.passworddirectly — must be REFUSED- Delete the illegal line, recompile, run — clean output
class InstaAccount{ private String password = "idli@2026"; void login(String attempt) { if (password.equals(attempt)) { System.out.println("Logged in!"); } else { System.out.println("Wrong password."); } }}public class PrivateDemo{ public static void main(String[] args) { InstaAccount acc = new InstaAccount(); acc.login("idli@2026"); // the front door — works System.out.println(acc.password); // the window — refused }}javac — line 24 gets the red underline the moment you type it, with the same message. The IDE and the compiler are enforcing one rule: private = same class only. Even a subclass (extends, Class 10) stays outside this ring.
Use case — when do I write private? Fields, almost always. A field is your class's inner state; letting outsiders write it raw is how a fest app ends up with registeredCount = -50. Hide the field, offer a method — the method can VALIDATE. That one sentence is the whole of Class 14, arriving early.
PART 6 · DEFAULT — THE KEYWORD THAT ISN'T THERE
Write nothing, get
the hostel-floor rule.
The speaker on your hostel floor: nobody carries a key for it, yet everyone ON the floor may use it — and someone from another hostel can't. Java's version: write no modifier at all and the member becomes package-private — visible to every class in the same package, invisible outside it.
A named folder of related classes — Java's way of grouping team code. The full mechanics (the package line, javac -d) arrive at Class 16. For now: package = the folder-family a class belongs to.
Every file since Lab 0 has no package line — they all share one unnamed home, the default package. So all our classes are "on the same floor", and default members flow freely between them.
Default's power only SHOWS at a package boundary — a class in another package simply cannot see the member. You'll feel that wall in Class 16 and push against it yourself in Lab 3.
MICRO-STORY — TEAMMATES ON THE SAME FLOOR (DEFAULT ACCESS, WORKING)
Use case — when is default right? Helper classes and members meant for teammates only — the fest app's SeatAllocator that only other event-code should touch, never outside apps. It is also the level you get by accident when you forget a modifier — which is why the exam loves asking about it. Its exam name: package-private.
PART 7 · PROTECTED — THE FAMILY KEY
protected: the floor,
plus every child — anywhere.
The family OTT password: everyone at home knows it (the "same package" part) — and so does your sibling in a Bengaluru PG (the "subclass in another package" part). protected is default's circle plus the extends family channel. This keyword exists because of Class 10.
MICRO-PAIR — THE CHILD IS IN, THE STRANGER IS OUT
THE MAP — WHY PROTECTED IS THE ONLY KEYWORD THAT CROSSES THE BORDER SELECTIVELY
Trace each arrow with a finger: green solid = allowed, red dashed = refused. The border itself never opens — only the family channel tunnels through it.
ONE RUNNABLE FILE — THE FAMILY CHANNEL, LIVE
class Player{ protected int fitnessScore = 82;}class Captain extends Player{ void preMatchReport() { System.out.println("Captain fitness: " + fitnessScore); }}public class ProtectedDemo{ public static void main(String[] args) { Captain rohit = new Captain(); rohit.preMatchReport(); }}fitnessScore, a delivery partner's base rating…) but the general public shouldn't touch. It is rarer than private/public in real code — and precisely because it sits mid-ladder, the exam loves it: P1·Q11b (protected + final) lands next class.
PART 8 · PUBLIC — THE NOTICE BOARD
public: pinned where
the whole world reads it.
The fest poster on the main-gate notice board — any student, any department, any visitor reads it. public is total visibility: every class, every package, forever. You have typed it since your first program without being told why. Today the debt is paid.
YOU'VE BEEN USING IT ALL SEMESTER — THREE OLD FRIENDS, DECODED ONE PRESS AT A TIME
public static void main(String[] args) — main is public because the JVM is an outsider. It lives outside every class you write; if main were private or default, the JVM couldn't call it and nothing would ever run.
System.out.println(...) — works from ANY class you have ever written. That is only possible because println is a public method of a public class in someone else's package (java.io). You have been consuming public API since Lab 0.
public class PrivateDemo — a public class must live in a file of the same name (the rule Notepad++ taught you the hard way in Class 2). One public class per file; its neighbours in the file stay default.
Public is a promise, not a convenience. Once a member is public, every codebase on Earth may call it — so you can never rename or remove it without breaking someone. Real engineers keep the public surface SMALL: methods meant to be called, and almost never bare fields.
It compiles, yes. It also means any code anywhere can set your fest app's registeredCount to -50 and your seat allocator crashes at 7pm on fest day. Visibility is DESIGN, not decoration: start from private and widen a member only when a real caller needs it. The exam phrases this exact idea as "use case of each specifier" — P2·Q11a, two parts from now.
PART 9 · THE MATRIX — PHOTOGRAPH THIS TABLE
Sixteen cells.
Every visibility question, answered.
Four keywords × four places a caller can stand = the whole topic in one table. This exact grid earns the marks in BOTH of today's PYQs, drives Lab 3, and returns in every unit after this one. Copy it into the notebook — by hand, all sixteen cells.
| MODIFIER | SAME CLASS | SAME PACKAGE | SUBCLASS (OTHER PKG) | WORLD (OTHER PKG) |
|---|---|---|---|---|
private | ✓ YES | ✗ NO | ✗ NO | ✗ NO |
| default (none) | ✓ YES | ✓ YES | ✗ NO | ✗ NO |
protected | ✓ YES | ✓ YES | ✓ YES | ✗ NO |
public | ✓ YES | ✓ YES | ✓ YES | ✓ YES |
See the staircase? Each row keeps every ✓ of the row above and adds exactly one more. Memorise the STAIRCASE, not sixteen separate cells.
protected × world = NO. Freshers assume protected is "almost public" — it is not. A non-subclass in another package sees nothing. That single cell is the highlighted row's exam value.
"Same class" is ALWAYS yes — no keyword locks a class out of itself. "Same package" today means our default package; from C16 it means an explicit com.college.* folder-family.
For any access check ask, in order: 1) where is the caller standing (class / package / subclass / world)? 2) what does that column say for this modifier's row? Two questions, zero doubt.
PART 10 · WORKED EXAMPLE — ONE CLASS, ALL FOUR LEVELS
CampusEventApp:
the fest app, member by member.
The Part-F spine arrives. One class from the college fest's event software, deliberately using ALL FOUR levels — and then we stand in each of the four caller positions and ask the matrix's two questions for every member.
class CampusEvent{ private String organizerContact = "98490xxxxx"; // diary private int registeredCount = 0; // diary String venue = "Main Auditorium"; // default — floor protected int volunteerSlots = 20; // family key public String eventName = "HackVasavi 2026"; // board public void register() { registeredCount = registeredCount + 1; System.out.println("Registered! Total: " + registeredCount); }}public class CampusEventApp{ public static void main(String[] args) { CampusEvent hack = new CampusEvent(); System.out.println(hack.eventName); // public — ✓ System.out.println(hack.venue); // default, same floor — ✓ hack.register(); // public method — ✓ // System.out.println(hack.organizerContact); ✗ private — won't compile }}private; the world gets a public METHOD instead of the raw counter. This is next class's encapsulation, already breathing.
THE WALKTHROUGH — FOUR CALLER POSITIONS, ONE PER PRESS (SOLUTION INCLUDED, PER ROSTER)
Same class ⇒ column 1 ⇒ every row says YES. It reads and rewrites the private registeredCount freely — a class always trusts itself.
Same package ⇒ column 2 ⇒ private says NO, everything else YES. It saw eventName, venue, could touch volunteerSlots — but both private fields are sealed.
Subclass elsewhere ⇒ column 3 ⇒ only protected + public survive. It inherits volunteerSlots and eventName; venue (default) vanishes at the package border, privates stay sealed.
World ⇒ column 4 ⇒ public only. It may read eventName and call register(). Nothing else exists for it — which is exactly what the fest team intended.
Same five members — four different worlds, depending only on where the caller stands. That is the whole topic.
PART 11 · EXAM CORNER — THIS EXACT QUESTION WAS ASKED
PYQ · "Discuss access specifiers
in detail." Four marks, four levels.
Everything this sheet needs, you built in the last seven parts. Watch the full-marks answer write itself point by point — definition line, all four levels with use cases, the matrix as a drawn figure, and (rule of this deck) a compilable model program with its real run.
Q11(a). Discuss access specifiers in detail. [4 M]
Definition: Access specifiers (also called access modifiers) are keywords that fix the visibility of a class member — which other classes may read a field or call a method. Java provides four levels.
1 · private: visible only inside the declaring class — not even a subclass sees it. Use case: sensitive state, e.g. organizerContact in an event class; outsiders reaching for it get compile-time refusal.
2 · default (no keyword): package-private — visible to every class in the same package, invisible outside it. Use case: helper members meant for teammates only, e.g. venue shared inside the event team's package.
3 · protected: same package plus every subclass, even in other packages — the inheritance channel. Use case: state a parent designs for its children, e.g. volunteerSlots for future event subclasses. Note: to a non-subclass outside the package it is invisible.
4 · public: visible everywhere — all classes, all packages. Use case: the intended API surface, e.g. register(); also why main must be public — the JVM calls it from outside every class.
FIG · EACH STEP KEEPS EVERY EARLIER AUDIENCE AND ADDS EXACTLY ONE MORE
Visibility table (the mark-earner): same class → all four YES; same package → all except private; subclass in another package → only protected + public; anywhere else → public only.
Order to remember: private < default < protected < public — each widens the circle by one audience. ✓
MODEL PROGRAM FOR THIS ANSWER (DECK RULE: EVERY PYQ CARRIES ONE) — ONE LINE PER PRESS
class Canteen{ private int cashInDrawer = 5000; String todaysSpecial = "Samosa"; protected int stockUnits = 120; public String name = "VCE Canteen"; public void audit() { System.out.println("Drawer: " + cashInDrawer); // own class — ✓ }}public class SpecifierTour{ public static void main(String[] args) { Canteen c = new Canteen(); System.out.println(c.name); // public — ✓ System.out.println(c.todaysSpecial); // default, same pkg — ✓ System.out.println(c.stockUnits); // protected, same pkg — ✓ c.audit(); // public method — ✓ // System.out.println(c.cashInDrawer); ✗ private — compile error }}PART 12 · EXAM CORNER — THE CODE-WRITING TWIN
PYQ · "Write a program showing modifiers
controlling visibility."
The examiner wants PROOF, not prose: a program where the modifiers demonstrably decide what compiles and what runs. Strategy first, on the sheet — then the model program, stepped line by line, with its genuine refusal and its genuine run.
Q12(b). Write a Java program that shows how access modifiers control the visibility of class members. [4 M]
Plan (write this as a comment header): one data class StudentRecord carrying all four modifier levels, one driver class beside it. The driver successfully reads the public, default and protected members — and the private attempt is shown refused by the compiler, kept as a comment quoting the exact error.
Key detail: both classes sit in one file, no package statement — the default package — so they share a package and three of the four levels are visible. The private member alone fails: that difference in outcome IS the modifiers controlling visibility.
Forward note (write it, earn goodwill): across different packages, default members would ALSO become invisible — the full cross-package demo needs the package statement, taught at Class 16 and exercised in Lab 3.
Program + real output on the next lines — reproduce both; the refusal comment is worth as much as the run. ✓
THE MODEL PROGRAM — ONE FILE, DEFAULT PACKAGE, ONE LINE PER PRESS
// P1·Q12b — modifiers controlling visibility (single file, default package)class StudentRecord{ private double cgpa = 8.9; // class only String section = "CSE-B"; // default: package protected int attendance = 91; // + subclasses public String rollNo = "24B81A05C7"; // everywhere public void showCgpa() { System.out.println("CGPA (via own method): " + cgpa); }}public class VisibilityDemo{ public static void main(String[] args) { StudentRecord r = new StudentRecord(); System.out.println("Roll (public): " + r.rollNo); System.out.println("Section (default): " + r.section); System.out.println("Attendance (protected): " + r.attendance); // System.out.println(r.cgpa); // ✗ REFUSED at compile time: // error: cgpa has private access in StudentRecord r.showCgpa(); // ✓ the class itself may use its private field }}PART 13 · ACTIVITY 1 — YOU ARE THE DESIGNER NOW
Six members, four keywords —
classify before you peek.
CLASSIFICATION · NOTEBOOK FIRST The fest team is extending CampusEvent. For each declared member below, write in your notebook the modifier its intended visibility demands — and ONE reason. Use the two-question drill: who needs it? which row gives exactly that circle, no wider?
eventId— unique ID other apps use to link to this event; read by everyone, never rewritten from outside.organizerContact— the organiser's personal phone number; only the class's own methods may touch it.registeredCount— the live head-count; must change ONLY viaregister(), or the seat allocator corrupts.venue— needed by the team's ownSeatAllocatorandNoticeBoardclasses (same package); outsiders shouldn't rely on it.volunteerSlots— future subclasses likeTechFestEvent(possibly in other packages) must tune it; strangers must not.register()— the one action the whole world is invited to perform.
Six verdicts + six reasons in ink. Then — and only then — unlock.
attempt first — classification is exactly what the internal exam's one-mark rapid-fire rounds test.
Everyone reads it, nobody rewrites it raw. World-readable ⇒ widest circle for reading. (A final lock on top would stop rewrites — Class 10's keyword pairing beautifully with today's.)
A personal phone number is the diary case — the innermost circle, no exceptions, not even subclasses.
"Must change only via register()" — hide the field, expose the method. Any wider and a stray line anywhere could set it to -50.
Teammates-in-the-same-package need it, outsiders must not depend on it — the hostel-floor level, written as NO keyword.
Subclasses in other packages must reach it, strangers must not — that is protected's exact circle, and nothing else's.
The intended API — the one door the world is supposed to knock on. Methods meant for everyone are public; that is what an API is.
Score yourself: 6/6 = designer's eye. Anything ≤4 — reread Part 9's staircase; every miss is one row of the matrix.
PART 14 · ACTIVITY 2 — FILL IN THE MISSING MODIFIERS
A UserProfile with blanks
where the keywords should be.
FILL-IN-CODE · NOTEBOOK FIRST A social-app teammate left the modifiers blank (____) in UserProfile. Copy the class into your notebook and fill each blank so the stated intent holds. Hint from the roster itself: some should stay private, one is public.
passwordHash— no code outside this class may ever read itemail— same: leaked emails = spam; only the class's own methods use itdisplayName— every screen in every package renders itlastLoginDay— the app team's own analytics classes (same package) read it; outsiders don't
Four blanks in ink, one reason each. Bonus question for the fast finishers: which blank is filled by writing nothing at all?
the compiler never guesses your intent — this activity is you learning to state it.
class UserProfile{ private String passwordHash; // never readable outside — diary private String email; // same — leak = spam public String displayName; // every screen, every package int lastLoginDay; // default — team analytics only}passwordHash and email are private — sensitive state, innermost ring (roster's "some stay private"). displayName is the one public member — it exists to be rendered everywhere. lastLoginDay is default: the bonus answer — you fill that blank by deleting it; no keyword IS the keyword.
displayName) is acceptable today, but Class 14 will show why real apps still prefer private + a getter — a display name has rules too (length, profanity). Hold that thought exactly one class.
Notepad++ or Eclipse — your pick since Lab 2. Either way, every refusal in this class should have happened on YOUR screen, not just this page.