Introduction & Syntax
Access Modifiers and Packages · Study material
Access modifiers decide who may use a class, field, method or constructor, and packages decide where code lives and how it is named. Together they let you build large Java applications from thousands of classes without name clashes and without every class poking at every other class's internals. Java has four access levels – public, protected, package-private (no keyword) and private – and a package system (com.learnfrenzy.billing) that maps to folders, controls package-private access and is organised with import statements. On top of packages, Java 9+ modules control which packages a library exports at all. These rules are core to encapsulation and are a favourite of interviews and certification exams. This page explains them with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- The four access levels and the access table
- private is per class; protected and inheritance
- Access and overriding
- Packages: declaring, naming and folders
- import, wildcard and static imports; name conflicts
- Classpath, JAR files and modules
The four access levels
| Modifier | Same class | Same package | Subclass in another package | Everywhere |
|---|---|---|---|---|
public | yes | yes | yes | yes |
protected | yes | yes | yes (through inheritance) | no |
| (none) package-private | yes | yes | no | no |
private | yes | no | no | no |
Top-level classes can only be public or package-private; members and nested classes can use all four. A file may contain at most one public top-level class, and its name must match the file name.
class Account {
public String holder; // public: everyone
protected String branch; // protected: same package + subclasses anywhere
String ifsc; // package-private (no keyword): same package only
private double balance; // private: this class only
Account(String holder, String branch, String ifsc, double opening) {
this.holder = holder; this.branch = branch; this.ifsc = ifsc; this.balance = opening;
}
public double getBalance() { return balance; } // controlled read access
public void deposit(double amt) { if (amt > 0) balance += amt; }
private String mask() { return holder.charAt(0) + "***"; } // helper, hidden from others
public String label() { return mask() + " @ " + branch; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Asha", "Pune", "LFB0001", 1000);
a.deposit(500);
// Main is in the same (unnamed) package, so public, protected and package-private members are visible
System.out.println(a.holder + " " + a.branch + " " + a.ifsc + " " + a.getBalance() + " " + a.label());
// a.balance or a.mask() would not compile: they are private to Account
}
}
Asha Pune LFB0001 1500.0 A*** @ Pune
private is per class
private restricts access to code inside the same top-level class – so one object can read another object's private fields of the same class (as equals methods do), and nested classes share private access with their outer class.
class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
// private means "private to the CLASS", not to the object:
// a Point method may read another Point's private fields
double distanceTo(Point other) {
int dx = x - other.x, dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
boolean sameAs(Point o) { return x == o.x && y == o.y; }
}
public class Main {
private static int secret = 42;
static class Helper { // a nested class can use the outer class's private members
int reveal() { return secret; }
}
public static void main(String[] args) {
Point p = new Point(0, 0), q = new Point(3, 4);
System.out.println(p.distanceTo(q) + " " + p.sameAs(new Point(0, 0)) + " " + new Helper().reveal());
}
}
5.0 true 42
protected and inheritance
A subclass inherits protected and public members and can use them directly. Private members are not accessible in the subclass, although they still exist inside the object and can be reached through the parent's public methods.
class Vehicle {
protected int speed; // visible to subclasses
private int serviceCount; // NOT visible to subclasses
protected void accelerate(int by) { speed += by; }
public void service() { serviceCount++; }
public int services() { return serviceCount; }
}
class Bike extends Vehicle {
void wheelie() {
accelerate(15); // inherited protected method
speed += 5; // inherited protected field
service(); // public method – changes the private field indirectly
}
}
public class Main {
public static void main(String[] args) {
Bike b = new Bike();
b.wheelie();
b.wheelie();
System.out.println(b.speed + " " + b.services());
}
}
40 2
Access and overriding
An overriding method may keep or widen the access of the method it overrides, never narrow it – otherwise code using the parent type could call a method the child has hidden. Order from narrowest to widest: private < package-private < protected < public. Private methods are not inherited, so they cannot be overridden at all.
class Shape {
protected String name() { return "shape"; }
double area() { return 0; } // package-private
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
@Override public String name() { return "square"; } // protected → public: widening is allowed
@Override protected double area() { return side * side; } // package-private → protected: allowed
// @Override private double area() { ... } // narrowing would NOT compile
}
public class Main {
public static void main(String[] args) {
Shape s = new Square(3);
System.out.println(s.name() + " " + s.area());
}
}
square 9.0
Packages
A package groups related types and gives them a unique namespace. Declare it as the first statement of a source file:
// File: src/com/learnfrenzy/billing/Invoice.java
package com.learnfrenzy.billing; // must be the first statement (comments aside)
import java.time.LocalDate; // imports come after the package statement
import com.learnfrenzy.customers.Customer;
public class Invoice { // public: usable from other packages
private final Customer customer;
private final LocalDate date = LocalDate.now();
public Invoice(Customer customer) { this.customer = customer; }
double taxRate() { return 0.18; } // package-private: only com.learnfrenzy.billing can call it
}
- Names are lower case and usually a reversed domain:
com.learnfrenzy.billing. - The folder structure must match:
src/com/learnfrenzy/billing/Invoice.java. - The fully qualified name of the class is
com.learnfrenzy.billing.Invoice. - A file without a package statement is in the unnamed package – fine for small experiments (and the programs on this page) but not for real projects.
- Packages are not nested in terms of access:
com.shopandcom.shop.cartare completely separate packages.
Imports
import only lets you use a short name instead of the fully qualified one – it does not copy code or load anything. java.lang is imported automatically. When two packages contain the same simple name (java.util.Date and java.sql.Date), import one and fully qualify the other.
import java.time.LocalDate; // single-type import
import java.util.*; // on-demand (wildcard) import of java.util
import static java.lang.Math.max; // static import of one member
public class Main {
public static void main(String[] args) {
List<String> langs = new ArrayList<>(List.of("Java", "C", "Python"));
Collections.sort(langs);
// java.util.Date and java.sql.Date share a simple name: use the fully qualified name for one of them
java.sql.Date sqlDate = java.sql.Date.valueOf("2026-01-26");
LocalDate d = sqlDate.toLocalDate();
// java.lang (String, Math, System, Integer …) is imported automatically
System.out.println(langs + " " + d.getDayOfWeek() + " " + max(7, 3) + " " + Integer.toBinaryString(10));
}
}
[C, Java, Python] MONDAY 7 1010
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
// Every class lives in a package; its fully qualified name = package + "." + simple name
System.out.println(String.class.getName() + " | " + String.class.getPackageName());
System.out.println(ArrayList.class.getName() + " | " + ConcurrentHashMap.class.getPackageName());
System.out.println("[" + Main.class.getPackageName() + "] " + Main.class.getSimpleName()); // the unnamed package
System.out.println(String.class.getModule().getName()); // JDK classes live in modules
}
}
java.lang.String | java.lang java.util.ArrayList | java.util.concurrent [] Main java.base
Compiling and running packaged code
# compile everything under src into out, keeping the package folders
javac -d out src/com/learnfrenzy/billing/*.java src/com/learnfrenzy/customers/*.java
# run using the FULLY QUALIFIED class name, with out on the classpath
java -cp out com.learnfrenzy.billing.App
# package the classes into a JAR and run it
jar --create --file billing.jar --main-class com.learnfrenzy.billing.App -C out .
java -jar billing.jar
# a module declaration (src/module-info.java) – Java 9+
module com.learnfrenzy.billing {
requires java.sql; // modules this one depends on
exports com.learnfrenzy.billing; // only exported packages are visible to other modules
}
Common mistakes
- Making every field public – breaks encapsulation; prefer private plus methods.
- Thinking protected means "subclasses only" – it also includes the whole package.
- Narrowing access when overriding – a compile error.
- Folder structure not matching the package – ClassNotFoundException or javac errors.
- Expecting
import com.shop.*to import sub-packages – it does not. - Importing two classes with the same simple name – a conflict.
- Running
java Invoiceinstead ofjava com.learnfrenzy.billing.Invoice.
Key points to remember
- public > protected > package-private > private.
- Top-level classes: public or package-private only; one public class per file, named like the file.
- private is per class; protected = package + subclasses.
- Overrides may widen access, never narrow it.
- The package statement comes first; folders mirror package names.
- Imports are a naming convenience; java.lang is automatic; wildcards do not include sub-packages.
Frequently asked questions
What is the default access in Java?
Package-private: no keyword, visible only inside the same package. (In interfaces, members are public by default.)
Does a wildcard import slow the program down?
No. Imports are resolved at compile time; the bytecode contains fully qualified names either way.
What do modules add?
A module's module-info.java lists the packages it exports; public classes in packages it does not export are inaccessible to other modules.
Where can I learn more?
Read Java Access Modifiers and Java Packages, then practise with the exercises below.