computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🏗️

🎓

⏱ 30 min

Free

Classes & Objects in Java

Create classes with fields, constructors and methods, and protect data with private.

🎯 What you will learn

  • Write classes with fields and constructors
  • Use private fields with getters
  • Create and use objects

👋 Let’s get started!

Java was built for object-oriented programming 🏗️. Every Android app is made of classes. Let’s design our own — and learn why pros keep fields private.

🪜 Step by step

1. 🧱 Fields & constructor

Fields store data; the constructor sets them up.

public class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
2. 🔒 Encapsulation

private hides data; public getters let others read it safely.

public String getName() {
    return name;
}
3. 🐕 Objects

new builds an object from the class.

Dog rex = new Dog("Rex", 3);
System.out.println(rex.getName());

🧪 Try it!

Read the code, guess what it prints, then press 👀 Show output.

Bank account

class BankAccount {
    private String owner;
    private double balance;

    BankAccount(String owner) {
        this.owner = owner;
    }

    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    boolean withdraw(double amount) {
        if (amount > balance) return false;
        balance -= amount;
        return true;
    }

    double getBalance() { return balance; }
}

// in main:
BankAccount acct = new BankAccount("Zoe");
acct.deposit(50);
System.out.println(acct.withdraw(80));
System.out.println(acct.withdraw(20));
System.out.println(acct.getBalance());

Getter method

public class Book {
    private String title;
    public String getTitle() {
        return title;
    }
}

📖 Key words

Tap a card to flip it over!

Field
A variable inside a class 🏷️
Constructor
Sets up a new object 🔨
private
Hidden from other classes 🔒
Encapsulation
Protecting data inside objects 🛡️

🏆 Challenge

Predict the output.

Challenge

class Counter {
    private int count = 0;
    void click() { count++; }
    int getCount() { return count; }
}
// main:
Counter c = new Counter();
c.click(); c.click(); c.click();
System.out.println(c.getCount());

Knowledge Check Quiz

  1. Which keyword creates an object?
  2. Why make fields private?
  3. What does this.name refer to?
Next lesson →