Classes and Objects
Classes are the heart of Java. Every Java program is built from classes and the objects created from them.
On this page · 5 min · Beginner
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 30, 2026
In simple words#
A class is the blueprint of a mobile phone model; objects are the actual phones made from it. Every phone has the same design but its own owner and battery level.
- Class
- Blueprint with fields and methods.
- Object
- An instance created with new.
- Reference
- A variable that points to an object.
Learning objectives#
- Define a class with fields and methods
- Create objects with new
- Understand references
- Override toString
Explanation#
Fields hold state (balance, owner); methods define behaviour (deposit, withdraw).
new BankAccount(...) creates an object on the heap and returns a reference.
Two variables can reference the same object — changes through one are seen through the other.
Override toString to give objects a readable text form.
Code example: A simple bank account#
public class BankAccount {
String owner;
double balance;
void deposit(double amount) {
balance += amount;
}
@Override
public String toString() {
return owner + ": ₹" + balance;
}
public static void main(String[] args) {
BankAccount a = new BankAccount();
a.owner = "Asha";
a.deposit(5000);
BankAccount b = a; // same object, second reference
b.deposit(1000);
System.out.println(a); // calls toString()
}
}
Asha: ₹6000.0
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- The class defines fields and a method.
- new creates an object.
- b points to the same object as a.
- toString controls printing.
Real-world use case#
Banking, e-commerce and HR systems model customers, orders and employees as classes.
Common mistakes#
Anyone can set balance = -100. Use encapsulation (next lessons).
b = a copies the reference, not the object.
Best practices#
- One class per concept
- Meaningful toString
- Keep fields private
- Small, focused methods
Remember this#
Class = blueprint; object = instance.
new creates; variables hold references.
Override toString for readable output.
Practice exercise#
Your task: Add a withdraw(double amount) method that only withdraws if the balance is enough.
Show solution
boolean withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
Mini quiz#
After b = a; b.deposit(100); what happens to a?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.