Classes and Objects in Java
A class describes the state and behaviour of a kind of thing, and an object is one concrete instance of that description held in memory.
-
Java Basics
- Introduction to Java
- Setting Up Java and Writing Your First Program
- Variables, Data Types and Literals in Java
- Type Casting and Type Conversion in Java
- Operators and Expressions in Java
- Input and Output in Java
- Comments, Keywords and Naming Conventions in Java
- Control Flow in Java: if, else and switch
- Loops in Java: for, while and do-while
- Methods
- Arrays and Strings
-
OOP
- Classes and Objects in Java
- Constructors in Java
- The this Keyword in Java
- The static Keyword in Java
- Encapsulation in Java
- Access Modifiers in Java
- Inheritance in Java
- Method Overriding and super in Java
- Polymorphism in Java
- Abstraction, Abstract Classes and Interfaces in Java
- Composition, Aggregation and Association in Java
- The Object Lifecycle in Java
- Core Java
- Exception Handling
-
Collections
- The Java Collections Framework
- List in Java: ArrayList, LinkedList, Vector and Stack
- Set in Java: HashSet, LinkedHashSet and TreeSet
- Map in Java: HashMap, LinkedHashMap and TreeMap
- How HashMap Works Internally in Java
- Queue and Deque in Java: ArrayDeque and PriorityQueue
- Iterators in Java
- Comparable and Comparator in Java
- Collections Utilities and Choosing the Right Collection
- Generics
- Java 8+
- Stream API
- Date and Time
- File and I/O
-
Multithreading
- Threads in Java: Processes, Runnable and Thread
- Thread Lifecycle in Java
- Synchronization in Java: synchronized and volatile
- Locks and Atomic Classes in Java
- Race Conditions and Deadlocks in Java
- The Executor Framework and Thread Pools in Java
- Future and CompletableFuture in Java
- Concurrent Collections in Java
- The Java Memory Model
- JVM and Memory
- Advanced Java
- Networking
- JDBC
- Testing
Definition
A class is a blueprint. It declares the data a thing holds, called fields, and the operations it supports, called methods. An object is a single instance created from that blueprint, with its own copy of the fields.
Why classes exist
- Related data and the code that operates on it live in one place.
- Internal details can change without breaking callers.
- The vocabulary of the program starts to match the vocabulary of the problem.
- Instances can be created, passed around and replaced independently.
Syntax
public class BankAccount {
// fields - the state of each object
private String holder;
private double balance;
// constructor - how an object is brought into a valid state
public BankAccount(String holder, double openingBalance) {
this.holder = holder;
this.balance = openingBalance;
}
// methods - the behaviour
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
}
public double getBalance() {
return balance;
}
}Creating and using objects
BankAccount first = new BankAccount("Meera", 5000);
BankAccount second = new BankAccount("Arun", 1200);
first.deposit(750);
System.out.println(first.getBalance()); // 5750.0
System.out.println(second.getBalance()); // 1200.0Each object carries its own holder and balance. The methods are shared; the data is not.
What new actually does
- Allocates memory on the heap for the object.
- Sets every field to its default value.
- Runs the field initialisers and any instance initialiser blocks.
- Runs the constructor body.
- Returns a reference to the finished object.
stack heap
----- ----
first ------------------> [ BankAccount: holder="Meera", balance=5750.0 ]
second ------------------> [ BankAccount: holder="Arun", balance=1200.0 ]The variable lives on the stack and holds a reference. The object lives on the heap. Two variables can reference one object, and an object with no references left becomes eligible for garbage collection.
Fields, local variables and parameters
| Kind | Declared | Lifetime | Default value |
|---|---|---|---|
| Instance field | In the class body | As long as the object | Yes |
| Static field | In the class body with static | As long as the class is loaded | Yes |
| Local variable | Inside a method | Until the block ends | No, must be assigned |
| Parameter | In the method header | For the call | Supplied by the caller |
Object identity, equality and state
BankAccount a = new BankAccount("Meera", 100);
BankAccount b = new BankAccount("Meera", 100);
BankAccount c = a;
System.out.println(a == b); // false - different objects
System.out.println(a == c); // true - the same object
c.deposit(50);
System.out.println(a.getBalance()); // 150.0 - a and c are one objectA more complete example
public class Book {
private final String title;
private final String author;
private int copiesAvailable;
public Book(String title, String author, int copiesAvailable) {
this.title = title;
this.author = author;
this.copiesAvailable = copiesAvailable;
}
public boolean lend() {
if (copiesAvailable == 0) {
return false;
}
copiesAvailable--;
return true;
}
public void returnCopy() {
copiesAvailable++;
}
@Override
public String toString() {
return title + " by " + author + " (" + copiesAvailable + " available)";
}
}Notice that lend protects the rule that copies never go negative. That rule lives inside the class, so no caller can break it.
Common mistakes
- Making fields
public, which lets any caller put the object into an invalid state. - Writing a class that is only a bag of getters and setters, with the real logic scattered elsewhere.
- Confusing the class with the object:
BankAccountholds no balance, an instance does. - Using an object reference before assigning it, which gives a
NullPointerException. - Putting unrelated responsibilities into one large class.
Best practices
- Keep fields
privateand expose only what callers genuinely need. - Make a field
finalwhen it must not change after construction. - Name classes after the concept, not after the pattern:
Invoicerather thanInvoiceManagerHelper. - Give a class one clear responsibility.
- Override
toStringso objects are readable in logs.
Practice
- Model a
Studentwith a roll number, name and marks, and a method that reports the grade. - Create two objects with identical field values and explain why
==isfalse. - What is printed if a field is read before the constructor assigns it?
- Add a rule to
BankAccountthat prevents withdrawing more than the balance, and say why the rule belongs in the class. - List the responsibilities of a class you have written and split it if there is more than one.
Conclusion
A class defines a type, and an object is one instance of it with its own state. Keep the state private, put the rules that protect it inside the class, and objects become reliable building blocks rather than data containers.