01 / 20

Organizing Classes
& Files in Java

Learn how to split your code across multiple classes and files for cleaner, more maintainable, and professional-grade Java programs.

Java

Why Organize Your Code?

Imagine writing a 1,000-line essay as a single paragraph: no headings, no chapters, no sections. Impossible to read, impossible to fix. The same is true for code. Splitting your program into multiple classes and files makes it:

Readable
Each file has a single, clear purpose that anyone can understand at a glance.
Maintainable
Bugs are easier to find when code is organized into focused, small units.
Reusable
A well-defined class can be dropped into other projects without modification.

What Is a Class?

A class is a blueprint that bundles together data (fields) and behavior (methods) into one logical unit. Think of it like a recipe card: it describes what something is and what it can do.

Dog Fields (Data) String name int age String breed Methods (Behavior) bark(), fetch(), sit()

The One Class, One File Rule

Java enforces a fundamental rule: each public class must live in its own file, and the filename must match the class name (including capitalization).

Dog.java public class Dog { ...fields, methods... } Cat.java public class Cat { ...fields, methods... } Main.java public class Main { ...main method... } MyProject/ all files in same folder

Anatomy of a Java File

Every .java file follows the same three-part structure, from top to bottom:

1
Package declaration (optional): groups related classes, like folders for files.
2
Import statements: bring in classes from other packages so you can use them.
3
Class definition: the actual class with its fields, constructors, and methods.
// 1. Package declaration package animals; // 2. Import statements import java.util.ArrayList; // 3. Class definition public class Dog { String name; public void bark() { System.out.println("Woof!"); } }

The Core Principle: Separation of Concerns

Separation of Concerns means each class should have one clear responsibility. A class that tries to do everything becomes a tangled mess. Instead, split responsibilities across classes:

✕ One Giant Class handles input, logic, display, file saving, validation... everything Hard to read, fix, or reuse Main.java: entry point Calculator.java: logic Display.java: output Validator.java: input checks ✓ Each class does one thing well

Classes vs. Objects

A common point of confusion: a class is the blueprint, while an object is a concrete instance built from that blueprint. You define a class once, then create many objects from it.

Class (Blueprint) Object (Instance)
Definition A template describing fields and methods A specific thing created from the template
Analogy Cookie cutter An actual cookie
Keyword class Dog { ... } new Dog()
How many? Defined once per file Created as many times as needed

How to Split Your Code

1
Identify responsibilities: list every distinct "thing" your program deals with (e.g., a student, a grade, a report).
2
Create one class per concept: give each "thing" its own class with relevant fields and methods.
3
Save each class in its own .java file: the filename must match the class name exactly.
4
Create a Main class: this is your entry point with the public static void main() method.
5
Instantiate and connect: in Main, create objects from your other classes and call their methods.

Example 1: Two-Class Program

Let's build a simple program with a Student class and a Main class.

Student.java
public class Student { String name; int grade; public Student(String n, int g) { name = n; grade = g; } public void introduce() { System.out.println( "I'm " + name + ", grade " + grade); } }
Main.java
public class Main { public static void main(String[] args) { Student s1 = new Student("Ali", 10); Student s2 = new Student("Mia", 11); s1.introduce(); s2.introduce(); } }

Example 2: Three-Class Program

A pet shop tracker: Pet stores data, PetShop manages a list, Main runs everything.

PetShopProject/ Pet.java // name, species, age PetShop.java // ArrayList of Pets Main.java // entry point
// Pet.java public class Pet { String name, species; int age; public Pet(String n, String s, int a) { name = n; species = s; age = a; } public String toString() { return name + " (" + species + ", age " + age + ")"; } }

Example 2: PetShop & Main

// PetShop.java import java.util.ArrayList; public class PetShop { ArrayList<Pet> pets = new ArrayList<>(); public void addPet(Pet p) { pets.add(p); } public void listAll() { for (Pet p : pets) System.out.println(p); } }
// Main.java public class Main { public static void main(String[] args) { PetShop shop = new PetShop(); shop.addPet(new Pet("Buddy", "Dog", 3)); shop.addPet(new Pet("Whiskers", "Cat", 5)); shop.listAll(); } }

Grouping with Packages

As projects grow, you group related classes into packages: folders that give classes a namespace. This prevents naming conflicts and adds structure.

src/ models/ services/ app/ Pet.java Owner.java PetShop.java Main.java import models.Pet; import services.PetShop;

Access Modifiers: Who Can See What?

When splitting code across files, access modifiers control which parts of a class are visible to other classes:

Modifier Same Class Same Package Other Packages
public ✓ ✓ ✓
protected ✓ ✓ ✕ (only subclasses)
(default) ✓ ✓ ✕
private ✓ ✕ ✕

Example 3: Encapsulation in Action

Here is a BankAccount class that hides its balance field and controls access through methods:

// BankAccount.java public class BankAccount { private double balance; // hidden from other classes public BankAccount(double initial) { balance = initial; } public double getBalance() { return balance; } public void deposit(double amount) { if (amount > 0) balance += amount; } public void withdraw(double amount) { if (amount > 0 && amount <= balance) balance -= amount; } }

Common Mistakes to Avoid

✕ Filename Mismatch
Naming the file student.java for public class Student. Java is case-sensitive: file must be Student.java.
✕ Two Public Classes
Putting two public classes in one file. Only one public class is allowed per .java file.
✕ Missing Import
Using a class from another package without importing it. You will get a "cannot find symbol" error.
✕ Everything Public
Making all fields public instead of private. This breaks encapsulation and lets any class corrupt your data.

Quick Reference Summary

Concept What It Does Example
Class Blueprint for objects public class Dog { }
.java File Stores exactly one public class Dog.java
Package Folder grouping related classes package models;
Import Brings in external classes import models.Dog;
Access Modifier Controls visibility private, public
main() Method Program entry point public static void main()

Question 1 of 5

A public class named Vehicle must be saved in which file?

Question 2 of 5

How many public classes can a single .java file contain?

Question 3 of 5

Two classes, Order and Product, are in the same folder with no package declarations. Does Order.java need to import Product?

Question 4 of 5

Which access modifier should you use for a field that only its own class should be able to read or modify?

Question 5 of 5

You have three classes: Player, Game, and Scoreboard. According to the separation of concerns principle, which class should contain the main() method?