Chapter 15: Packages
Hey Webliance! Welcome to Chapter 15: Packages — this is the chapter where your Java projects start looking professional, organized, and scalable, just like how real companies structure their code.
Imagine we’re sitting together in a cozy Mumbai café — it’s evening, the city lights are coming on, and I’m going to explain packages like I’m teaching my younger brother who’s just starting to build bigger projects.
We’ll go super slowly, with lots of real-life analogies, complete step-by-step examples, folder structures, commands you can run, common mistakes with fixes, and plenty of code you can copy-paste and try right now.
Let’s dive in!
1. What is a Package? (The Big Idea)
A package is simply a folder (directory) that groups related Java classes, interfaces, and other packages together.
Real-life analogy: Think of packages like drawers in a big cupboard:
- One drawer for clothes (com.company.clothing)
- One for kitchen items (com.company.kitchen)
- One for electronics (com.company.electronics)
Without packages → everything is thrown on the floor → messy and hard to find. With packages → everything is neatly organized in drawers → easy to manage.
Why use packages?
- Avoid name conflicts — two classes can have the same name if they are in different packages
- Organize code — group related classes (e.g., all database-related classes in one package)
- Access control — use default and protected access only within the same package
- Namespace — real-world projects have thousands of classes; packages prevent chaos
2. Creating a Package (Step-by-Step)
Rule #1: The package name must match the folder structure exactly.
Example Project Structure (recommended real-world style):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
MyProject/ ├── src/ │ └── com/ │ └── webliance/ │ ├── banking/ │ │ ├── BankAccount.java │ │ └── SavingsAccount.java │ └── util/ │ └── DateUtils.java └── Main.java (can be in default package or inside a package) |
Step-by-Step: Create Your First Package
- Create folder structure:
- Inside your project folder → create folders: src → com → webliance → banking
- Create a class inside the package File: src/com/webliance/banking/BankAccount.java
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// This line MUST be the very first non-comment line! package com.webliance.banking; public class BankAccount { private double balance; public BankAccount(double initialBalance) { this.balance = initialBalance; } public void deposit(double amount) { if (amount > 0) { balance += amount; System.out.println("Deposited ₹" + amount + ". Balance: ₹" + balance); } } public double getBalance() { return balance; } } |
Notice:
- package com.webliance.banking; → matches the folder path exactly
- Dots (.) in package name = folder separators (/)
- Create another class in same package File: src/com/webliance/banking/SavingsAccount.java
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.webliance.banking; public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double initialBalance, double interestRate) { super(initialBalance); this.interestRate = interestRate; } public void addInterest() { double interest = getBalance() * (interestRate / 100); deposit(interest); System.out.println("Added interest: ₹" + interest); } } |
3. Using Classes from a Package – Import Statements
To use a class from another package, you must import it.
Three ways to import:
| Import Type | Syntax | When to use |
|---|---|---|
| Specific class | import com.webliance.banking.BankAccount; | Best practice — clear & safe |
| All classes in package (wildcard) | import com.webliance.banking.*; | Convenient, but can cause name conflicts |
| Static import (rare for now) | import static java.lang.Math.PI; | For constants/methods |
Example: Using the classes in Main.java
Option 1: Full qualified name (no import)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { com.webliance.banking.BankAccount acc = new com.webliance.banking.BankAccount(10000); acc.deposit(5000); } } |
Option 2: Using import (recommended) File: Main.java (can be in default package or any other package)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import com.webliance.banking.BankAccount; import com.webliance.banking.SavingsAccount; public class Main { public static void main(String[] args) { BankAccount acc = new BankAccount(10000); acc.deposit(5000); SavingsAccount savings = new SavingsAccount(20000, 4.5); savings.addInterest(); } } |
Option 3: Wildcard import
|
0 1 2 3 4 5 6 7 8 9 10 |
import com.webliance.banking.*; public class Main { // same code as above } |
4. Compiling & Running with Packages (Command Line)
Important: You must compile from the parent folder of src (or use IDE).
Command Line Steps (if not using IDE):
- Go to project root folder (where src is)
- Compile:
Bash0123456javac -d . src/com/webliance/banking/*.java src/*.java
-d . → creates .class files in the same package folders
- Run:
Bash0123456java com.webliance.banking.BankAccount # if it had main
or
Bash0123456java Main
Using IDE (IntelliJ / Eclipse / VS Code):
- IntelliJ: Right-click project → New → Package → type com.webliance.banking
- It auto-creates folders and adds package statement
- Run normally — IDE handles everything
5. Default Package vs Named Packages
- Classes without package statement are in the default package
- You cannot import classes from default package into named packages
- Best practice: Always put classes in named packages (except very small scripts)
6. Quick Recap Table (Your Cheat Sheet)
| Concept | Rule / Best Practice | Example |
|---|---|---|
| Package Declaration | First line: package com.company.project; | package com.webliance.banking; |
| Folder Structure | Must match package name (dots = folders) | com/webliance/banking/BankAccount.java |
| Import Specific Class | import com.webliance.banking.BankAccount; | Recommended |
| Wildcard Import | import com.webliance.banking.*; | Convenient but risk of conflicts |
| Access Within Package | default (no modifier) & protected visible | Classes in same package can access them |
| Running with packages | java full.package.ClassName | java com.webliance.banking.Main |
7. Common Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| Wrong package name vs folder | Compile error: “class … is public, should be declared in file…” | Make sure folder path matches package exactly |
| No package statement | Class goes to default package → hard to import | Always add package …; |
| Import name conflict | Two classes with same name | Use specific import or full qualified name |
| Compiling from wrong directory | “cannot find symbol” | Compile from project root with -d . |
| Using wildcard * carelessly | Unexpected class picked | Prefer specific imports |
8. Homework for You (Practice to Master!)
- Basic: Create package com.webliance.utils with class MathUtils having static methods add, multiply.
- Medium: Create package com.webliance.models with Person and Employee classes. Import and use them in Main.java.
- Advanced: Create two packages: com.webliance.banking and com.webliance.shop. Make a class in shop use BankAccount from banking.
- Fun: Create package com.webliance.games with classes Player, Game. Use them in a small program.
- Challenge: Try compiling and running the banking example from command line (without IDE) — share any error you get!
You’re doing amazing! Packages are what separate hobby code from professional, enterprise-level Java code — now your projects can grow without becoming a mess.
