Course contentsShow
← Java
Lesson 315 of 2,8708. Classes and EncapsulationFree lesson

Putting It Together: A Complete Class Example

Building a complete class with fields, methods, and a constructor to solidify fundamental concepts.

Putting It Together: A Complete Class Example

You'll learn how to combine fields, methods, and constructors into one working class that creates useful objects.

The Big Picture

You've learned about fields (the data an object holds), methods (what an object can do), and constructors (how objects are born). Now it's time to see them working together in a complete, practical example. Think of it like assembling all the parts of a bicycle: you've seen the wheels, handlebars, and frame separately—now you're putting them together to make something you can actually ride.

A Complete Class Example

public class BankAccount {
    // Fields: what each account has
    String accountHolder;
    double balance;
    
    // Constructor: how we create a new account
    public BankAccount(String holder, double initialBalance) {
        accountHolder = holder;
        balance = initialBalance;
    }
    
    // Method: what an account can do
    public void deposit(double amount) {
        balance = balance + amount;
    }
    
    // Method: another behavior
    public void withdraw(double amount) {
        balance = balance - amount;
    }
    
    // Method: checking the state
    public double getBalance() {
        return balance;
    }
}

Using the Complete Class

// Create two different bank accounts
BankAccount alice = new BankAccount("Alice", 500.0);
BankAccount bob = new BankAccount("Bob", 1000.0);

// Each object has its own state
alice.deposit(200.0);
bob.withdraw(150.0);

System.out.println(alice.getBalance());  // 700.0
System.out.println(bob.getBalance());    // 850.0

Each object maintains its own accountHolder and balance, completely independent of other BankAccount objects.

Key Takeaway: A complete class bundles fields (data), a constructor (initialization), and methods (behavior) into a reusable blueprint that creates independent objects, each with its own state.