Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 5

public, protected, package-private, private

Reading the visibility matrix without memorising it

22m55 XP
→→→

What you'll be able to do

  • List the four access levels from most open to most closed
  • Decide, for a given piece of code, whether an access is legal
  • Explain what a package is and what package-private means
  • Choose the right modifier for fields, methods and classes
1

Access Modifiers

The four levels and the one matrix that decides everything

Java asks one question about every access: 'from where are you asking?' The four modifiers are just four different answers.

An access modifier is a keyword you put in front of a field, method, constructor or class to say who may use it. Before the matrix, one word you need: a package is a named folder of related classes (package com.bank.core; at the top of the file). Classes in the same package are considered 'neighbours' by the compiler. The four levels, from most open to most closed:

public
Anyone, anywhere. Use for the API you *intend* other code to call.
protected
Same package plus subclasses — even subclasses in another package. Use for internals a child class legitimately needs.
(no modifier) — package-private
Only classes in the same package. This is the default when you write nothing at all.
private
Only inside the same class. The safest default for fields.

The visibility matrix

Access fromprivatepackage-privateprotectedpublic
Same class✅✅✅✅
Another class, same package❌✅✅✅
Subclass, same package❌✅✅✅
Subclass, different package❌❌✅ (through inheritance)✅
Unrelated class, different package❌❌❌✅

Read it as a staircase: each level down adds one more group of callers. The only row people get wrong is the fourth — see the callout below.

All four in one class

Main.java
1public class Employee {
2 private double salary;
3 protected String department;
4 String badgeId;
5 public String name;
6
7 private double taxRate() {
8 return 0.14;
9 }
10
11 public double netSalary() {
12 return salary - salary * taxRate();
13 }
14}
public class Employee {
A public class can be used from any package. Only one public class per .java file, and it must match the file name.
private double salary;
The most sensitive data — nothing outside Employee can read or write it, not even a subclass.
protected String department;
Subclasses such as Manager may use it directly; unrelated classes in other packages may not.
String badgeId;
No modifier = package-private. Visible to classes in the same package only. Perfect for helpers inside one module.
public String name;
Legal, but a design smell: it is the open drawer from Module 4. Prefer private + accessor.
private double taxRate() {
Modifiers apply to methods too. This is an internal helper, invisible outside the class — so you can change or delete it freely.
public double netSalary() {
The public contract. Inside the class it may freely use the private field *and* the private method.
Private inside, public outside

Run it. Then add `System.out.println(t.celsius);` in main and read the compiler error — that is the matrix being enforced.

Output
Press Run to execute this example.

The protected subtlety interviewers love

A subclass in another package may access a protected member through inheritance (this.department, or department), but *not* through a reference to some other Employee object (otherEmployee.department). Protected says 'you may use what you inherited', not 'you may inspect every instance'.

2

Package-private Access

Choosing a modifier on purpose

The right question is never 'what works?' — everything works with public. It is 'what is the smallest audience that can do the job?'

A decision procedure you can apply in seconds

  1. Start every field at private. If nothing breaks, you are done.
  2. Needed by a *subclass*? Prefer a protected method over a protected field — behaviour can validate, a field cannot.
  3. Needed by a *neighbour class* in the same module? Leave it package-private and keep it out of your public API.
  4. Needed by *outside code*? Make it public — and accept that you now support it forever.

protected field vs protected method

protected double balance;

every subclass can corrupt it

Main.java
1class Savings extends Account {
2 void hack() {
3 balance = -1; // allowed!
4 }
5}
  • Subclasses bypass all validation
  • You can never change the field's type or name safely
  • Bugs appear in classes you do not own

private field + protected method

subclasses get behaviour, not raw state

Main.java
1class Savings extends Account {
2 void addInterest() {
3 credit(getBalance() * 0.05);
4 }
5}
  • Validation still runs
  • Internals stay changeable
  • The parent keeps its invariants

Practical drills — is this access allowed?

SituationAllowed?Reason
Main (same package) reads a package-private field✅same package is enough
Manager extends Employee (other package) reads this.department (protected)✅inherited member
Manager (other package) reads other.department on another Employee❌not through inheritance
A subclass reads the parent's private field❌private never crosses the class boundary
A class in another package calls a public method✅public means everyone
A class in another package touches a package-private method❌different package

In this playground everything shares one file

The sandbox compiles your classes together as if they were in one package, so package-private and protected behave like 'visible'. private is still enforced, and the concept checker verifies your modifiers by reading the code — so write the modifier you would write in a real project.

Prove it — coding challenges

Common mistakes

WrongThinking `protected` is 'more private' than package-private.
Why`protected` is *wider*: same package **plus** subclasses anywhere.
FixOrder them: private < package-private < protected < public.
WrongMaking fields public 'just for now' to get the code compiling.
WhyPublic is a promise; every caller that appears meanwhile makes it permanent.
FixAdd a method instead — it is the same amount of typing and keeps the rules.
WrongWriting `private` on a class you want other files to use.
WhyTop-level classes may only be `public` or package-private — `private class Foo {}` at file level does not compile.
FixUse `public class` for shared classes, or no modifier for module-internal ones.

Lesson playground

Free practice

An Employee with all four levels, and a Manager subclass that uses what it is allowed to use. Try replacing `getSalary()` in describe() with `salary` and read the error.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

Report is in package com.app.web. Invoice is in package com.app.core and has a protected String code;. Report does not extend Invoice. Can Report read code?

Summary

  • Order of openness: private < package-private (no modifier) < protected < public.
  • A package is a named group of classes; sub-packages are separate packages.
  • `protected` = same package + subclasses, and only through inheritance for outside-package subclasses.
  • Default to private, widen only for a concrete, named caller.