Unit 2 home
CLASS 13 · PART F UNIT-2 OPENS · ACCESS MODIFIERS UNIT II · UI24PC320CS
CLASS 13 · P 1/14PGDN NEXT POINT · PGUP BACK
Vasavi College of Engineering · CSE-B · Object Oriented Programming through Java

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.

TODAY'S QUESTIONWho is allowed to read or call each member of a class?
THE FOUR LEVELSprivate · default · protected · public
PYQS SOLVED TODAYP2·Q11a (4m) · P1·Q12b (4m)
FEEDS FORWARDC14 encapsulation · C16 packages · LAB 3
UNIT 2 C13 · MODIFIERS C14 · ENCAPSULATION C15 · C16 LAB 3 · PACKAGES

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.

Class 13 — access modifiers

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.

Class 14 — encapsulation

The payoff. Hide the state with private, guard every change with validated methods — and a canteen-card balance becomes physically impossible to over-spend.

Part-F spine · CampusEventApp

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?

Part-F spine · CanteenCard

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 access compile 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 key
  • public — everywhere, the notice board
  • The full visibility matrix — photograph-this table
  • Worked example — CampusEventApp with 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

WHY "DEFAULT PACKAGE" TODAY? Every file you have written since Lab 0 lives in Java's 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:

public — THE WHOLE WORLD (every class, every package) protected — same package + EVERY subclass anywhere default (no keyword) — same package only private — SAME CLASS ONLY the innermost circle — even a subclass stays outside smaller circle = stronger protection

Read it inside-out: each keyword UNLOCKS one more ring. private < default < protected < public — memorise the order, half the matrix is already yours.

private — the diary

Visible ONLY inside the class that declares it. Not to subclasses, not to neighbours — nobody. The default choice for fields.

default — the hostel floor

Write NO keyword and the member is package-private: every class in the same package sees it; everyone outside is refused.

protected — the family key

Everything default gives, PLUS every subclass — even one living in a different package. Built for the extends family channel.

public — the notice board

Visible from every class in every package, forever. The right choice ONLY for the members you intend the world to call.

Modifier or specifier? Same thing.

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)

INSIDE THE OWN CLASS — ALWAYS WELCOME
class GamerTag
{
private int rank = 7;
void brag()
{
System.out.println("Rank " + rank);
}
}
Same class, full access. brag() reads rank freely — private never locks a class out of its own members.
ANY OTHER CLASS — REFUSED AT COMPILE TIME
class Rival
{
void peek(GamerTag g)
{
System.out.println(g.rank); // ✗ refused
}
}
Different class — even in the same file, same folder. The compiler stops this line: rank has private access in GamerTag. Not a runtime crash — the program never even builds.

NOW THE REAL FILE — WATCH THE COMPILER SAY NO, THEN YES

MINI PROBLEM · PRIVATEDEMO
STORY
An Insta-style account stores its password. Prove — with the compiler as your witness — that no outside class can read it, while the class itself uses it happily.
REQUIREMENTS
  • InstaAccount holds private String password
  • Its own method login() uses the password — must work
  • main first tries to read acc.password directly — must be REFUSED
  • Delete the illegal line, recompile, run — clean output
SAVE AS · NOTEPAD++ OR ECLIPSE — YOUR CHOICE SINCE LAB 2C:\Users\diya\Desktop\java-practice\class-13\PrivateDemo.java
PrivateDemo.java — one line per press
1class InstaAccount
2{
3 private String password = "idli@2026";
4
5 void login(String attempt)
6 {
7 if (password.equals(attempt))
8 {
9 System.out.println("Logged in!");
10 }
11 else
12 {
13 System.out.println("Wrong password.");
14 }
15 }
16}
17
18public class PrivateDemo
19{
20 public static void main(String[] args)
21 {
22 InstaAccount acc = new InstaAccount();
23 acc.login("idli@2026"); // the front door — works
24 System.out.println(acc.password); // the window — refused
25 }
26}
COMMAND PROMPT — THE REFUSAL, THEN THE FIX
C:\Users\diya\Desktop\java-practice\class-13> javac PrivateDemo.java
PrivateDemo.java:24: error: password has private access in InstaAccount
System.out.println(acc.password); // the window — refused
^
1 error
The compiler refuses to even BUILD the peek. Now delete line 24 and recompile:
C:\Users\diya\Desktop\java-practice\class-13> javac PrivateDemo.java
C:\Users\diya\Desktop\java-practice\class-13> java PrivateDemo
Logged in!
Eclipse users: you don't even reach 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.

Wait — what's a package?

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.

Where do OUR files live?

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.

The invisible refusal

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)

SAME PACKAGE — FREE FLOW
class MessMenu
{
String today = "Veg Biryani"; // no keyword = default
}
class NoticeBoard
{
void post(MessMenu m)
{
System.out.println("Today: " + m.today); // ✓ same floor
}
}
Both classes share the default package, so NoticeBoard reads today with zero ceremony. Handy for close teammates — but notice: NOTHING stops any same-floor class from also overwriting it.
ANOTHER PACKAGE — REFUSED (FULL DEMO AT C16)
// imagine a future Class-16 file that starts with:
// package com.college.app;
class OutsiderApp
{
void tryRead(MessMenu m)
{
System.out.println(m.today); // ✗ not visible here
}
}
Forward note (kept honest): we can't RUN this refusal yet — writing a second package needs Class 16's package statement. The full cross-package demo lands at Class 16 / Lab 3; today, trust the matrix row.

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

SUBCLASS — INHERITS THE KEY
class Player
{
protected int fitnessScore = 82;
}
class Captain extends Player
{
void report()
{
System.out.println("Fitness: " + fitnessScore); // ✓ family
}
}
Captain is-a Player (Class 10's test), so the protected field is simply THERE for it — its own inherited copy, no getter needed. This works even if Captain later moves to another package.
NOT FAMILY, NOT FLOOR — REFUSED
// a class in ANOTHER package, with no extends:
class FanPage
{
void leak(Player p)
{
System.out.println(p.fitnessScore); // ✗ refused
}
}
No is-a, no floor, no access. A stranger class in a foreign package hits fitnessScore has protected access in Player. (In OUR one default package a neighbour would see it — protected includes the whole floor.)

THE MAP — WHY PROTECTED IS THE ONLY KEYWORD THAT CROSSES THE BORDER SELECTIVELY

PACKAGE A — Player's home floor PACKAGE B — across the border Player protected fitnessScore Coach neighbour — same floor Captain extends Player — family extends channel ✓ FanPage no extends, no floor ✗ refused protected crosses the border ONLY along an extends arrow

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

SAVE ASC:\Users\diya\Desktop\java-practice\class-13\ProtectedDemo.java
ProtectedDemo.java — one line per press
1class Player
2{
3 protected int fitnessScore = 82;
4}
5
6class Captain extends Player
7{
8 void preMatchReport()
9 {
10 System.out.println("Captain fitness: " + fitnessScore);
11 }
12}
13
14public class ProtectedDemo
15{
16 public static void main(String[] args)
17 {
18 Captain rohit = new Captain();
19 rohit.preMatchReport();
20 }
21}
COMMAND PROMPT
C:\Users\diya\Desktop\java-practice\class-13> javac ProtectedDemo.java
C:\Users\diya\Desktop\java-practice\class-13> java ProtectedDemo
Captain fitness: 82
The child reached the parent's protected field directly — no getter, no cast, no fuss. That inherited channel is the entire reason protected exists.
Use case — when do I write protected? When a parent designs a member for its children: state a subclass legitimately needs to read or tune (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

FRIEND 1

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.

FRIEND 2

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.

FRIEND 3

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.

THE RULE

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.

The fresher's trap: "public everything, it just works".

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.

MODIFIERSAME CLASSSAME PACKAGESUBCLASS (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.

private same class default + same package protected + subclasses anywhere public + the world each step up keeps every audience below and adds exactly ONE more
The only tricky cell

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.

Reading the columns

"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.

Two-question drill

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.

SAVE ASC:\Users\diya\Desktop\java-practice\class-13\CampusEventApp.java
CampusEventApp.java — one line per press
1class CampusEvent
2{
3 private String organizerContact = "98490xxxxx"; // diary
4 private int registeredCount = 0; // diary
5 String venue = "Main Auditorium"; // default — floor
6 protected int volunteerSlots = 20; // family key
7 public String eventName = "HackVasavi 2026"; // board
8
9 public void register()
10 {
11 registeredCount = registeredCount + 1;
12 System.out.println("Registered! Total: " + registeredCount);
13 }
14}
15
16public class CampusEventApp
17{
18 public static void main(String[] args)
19 {
20 CampusEvent hack = new CampusEvent();
21 System.out.println(hack.eventName); // public — ✓
22 System.out.println(hack.venue); // default, same floor — ✓
23 hack.register(); // public method — ✓
24 // System.out.println(hack.organizerContact); ✗ private — won't compile
25 }
26}
COMMAND PROMPT
C:\Users\diya\Desktop\java-practice\class-13> javac CampusEventApp.java
C:\Users\diya\Desktop\java-practice\class-13> java CampusEventApp
HackVasavi 2026
Main Auditorium
Registered! Total: 1
Uncomment line 24 to watch the refusal: organizerContact has private access in CampusEvent. The organiser's phone number stays where it belongs — and registrations can ONLY move through register(), one at a time.
Notice the design story: the two dangerous members (a personal phone number, a count that must never be corrupted) are 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)

Caller 1 · register() — inside CampusEvent itself

Same class ⇒ column 1 ⇒ every row says YES. It reads and rewrites the private registeredCount freely — a class always trusts itself.

SEES ALL 5 MEMBERS
Caller 2 · CampusEventApp.main — neighbour class, same (default) package

Same package ⇒ column 2 ⇒ private says NO, everything else YES. It saw eventName, venue, could touch volunteerSlots — but both private fields are sealed.

SEES 3 OF 5
Caller 3 · a future TechFestEvent extends CampusEvent, in another package

Subclass elsewhere ⇒ column 3 ⇒ only protected + public survive. It inherits volunteerSlots and eventName; venue (default) vanishes at the package border, privates stay sealed.

SEES 2 OF 5
Caller 4 · some third-party FestAggregatorApp — other package, no extends

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.

SEES 1 FIELD + 1 METHOD

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.

PREVIOUS YEAR QUESTION — SOLVED ON THE SHEET PAPER 2 · Q11(a)4 MARKSREVISIT ← PARTS 4–9
the staircase table = 2 of the 4 marks!

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.

private default + same package protected + subclasses anywhere public + the whole world same class only

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

SpecifierTour.java — quote this if the examiner asks for an example
1class Canteen
2{
3 private int cashInDrawer = 5000;
4 String todaysSpecial = "Samosa";
5 protected int stockUnits = 120;
6 public String name = "VCE Canteen";
7
8 public void audit()
9 {
10 System.out.println("Drawer: " + cashInDrawer); // own class — ✓
11 }
12}
13
14public class SpecifierTour
15{
16 public static void main(String[] args)
17 {
18 Canteen c = new Canteen();
19 System.out.println(c.name); // public — ✓
20 System.out.println(c.todaysSpecial); // default, same pkg — ✓
21 System.out.println(c.stockUnits); // protected, same pkg — ✓
22 c.audit(); // public method — ✓
23 // System.out.println(c.cashInDrawer); ✗ private — compile error
24 }
25}
SAMPLE OUTPUT — QUOTE IT UNDER THE PROGRAM
C:\Users\diya\Desktop\java-practice\class-13> javac SpecifierTour.java
C:\Users\diya\Desktop\java-practice\class-13> java SpecifierTour
VCE Canteen
Samosa
120
Drawer: 5000
Line 10 proves private works INSIDE its class; the commented line 23 names the refusal outside it. One program, all four levels demonstrated — fresh domain (canteen), same staircase.
Marks map (4M): definition of specifiers 1m · four levels each in one line with a use case 2m · visibility table or program evidence 1m. Depth costs nothing extra — you already own all of it.

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.

PREVIOUS YEAR QUESTION — SOLVED ON THE SHEET PAPER 1 · Q12(b)4 MARKSREVISIT ← PARTS 4–9
show a ✓ AND a ✗ — that's "controlling"!

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

SAVE AS · NOTE: NO PACKAGE LINE, ON PURPOSEC:\Users\diya\Desktop\java-practice\class-13\VisibilityDemo.java
VisibilityDemo.java — the full-marks answer
1// P1·Q12b — modifiers controlling visibility (single file, default package)
2class StudentRecord
3{
4 private double cgpa = 8.9; // class only
5 String section = "CSE-B"; // default: package
6 protected int attendance = 91; // + subclasses
7 public String rollNo = "24B81A05C7"; // everywhere
8
9 public void showCgpa()
10 {
11 System.out.println("CGPA (via own method): " + cgpa);
12 }
13}
14
15public class VisibilityDemo
16{
17 public static void main(String[] args)
18 {
19 StudentRecord r = new StudentRecord();
20 System.out.println("Roll (public): " + r.rollNo);
21 System.out.println("Section (default): " + r.section);
22 System.out.println("Attendance (protected): " + r.attendance);
23 // System.out.println(r.cgpa); // ✗ REFUSED at compile time:
24 // error: cgpa has private access in StudentRecord
25 r.showCgpa(); // ✓ the class itself may use its private field
26 }
27}
SAMPLE OUTPUT — REAL RUN
C:\Users\diya\Desktop\java-practice\class-13> javac VisibilityDemo.java
C:\Users\diya\Desktop\java-practice\class-13> java VisibilityDemo
Roll (public): 24B81A05C7
Section (default): CSE-B
Attendance (protected): 91
CGPA (via own method): 8.9
Three direct reads succeed, the private one is refused (lines 23–24 quote the exact error), and the CGPA still reaches the screen — but only through the class's OWN public method. Visibility controlled, demonstrated, four marks.
Why not show a cross-package failure too? Because packages aren't taught yet — and the answer doesn't need them: all four levels are distinguishable in one default-package file, as the run proves. The one-line forward note ("full cross-package demo at Class 16 / Lab 3") tells the examiner you know exactly where the story continues.

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 via register(), or the seat allocator corrupts.
  • venue — needed by the team's own SeatAllocator and NoticeBoard classes (same package); outsiders shouldn't rely on it.
  • volunteerSlots — future subclasses like TechFestEvent (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.

SOLUTION SHEET · ACTIVITY 1 — THE DESIGNER'S VERDICTS
eventId

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.)

public
organizerContact

A personal phone number is the diary case — the innermost circle, no exceptions, not even subclasses.

private
registeredCount

"Must change only via register()" — hide the field, expose the method. Any wider and a stray line anywhere could set it to -50.

private
venue

Teammates-in-the-same-package need it, outsiders must not depend on it — the hostel-floor level, written as NO keyword.

default
volunteerSlots

Subclasses in other packages must reach it, strangers must not — that is protected's exact circle, and nothing else's.

protected
register()

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.

public

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.

THE GAPPED FILE — UserProfile.java
INTENT
  • passwordHash — no code outside this class may ever read it
  • email — same: leaked emails = spam; only the class's own methods use it
  • displayName — every screen in every package renders it
  • lastLoginDay — the app team's own analytics classes (same package) read it; outsiders don't
class UserProfile
{
____ String passwordHash;
____ String email;
____ String displayName;
____ int lastLoginDay;
}

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.

SOLUTION SHEET · ACTIVITY 2 — THE COMPLETED FILE
UserProfile.java — completed, one line per press
1class UserProfile
2{
3 private String passwordHash; // never readable outside — diary
4 private String email; // same — leak = spam
5 public String displayName; // every screen, every package
6 int lastLoginDay; // default — team analytics only
7}
The verdicts, reasoned: 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.
One design smell to name out loud: a public FIELD (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.
YOUR PRACTICE FOLDER — UNIT 2'S FIRST ENTRIES
Desktop\java-practice\
class-12\ — RankedAccount, FoodApp … (Unit 1's close)
class-13\
PrivateDemo.java — the refusal you compiled yourself
ProtectedDemo.java — the family channel, live
CampusEventApp.java — all four levels in one class
SpecifierTour.java — PYQ P2·Q11a's model program
VisibilityDemo.java — PYQ P1·Q12b's full-marks answer

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.