Java OOP
Classes & Objects
Complete lesson for Classes & Objects using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Classes & Objects
Section: Java OOP. Java classes and objects — class as a blueprint, objects as real instances, real-life examples, syntax, new and heap memory, members, structure vs class, records, and the Object class.
What is a class?
- A class is a user-defined data type and a blueprint (template) that describes what its objects will have (state / fields) and what they can do (behaviour / methods).
- A class is a logical idea. Declaring it does not create any object or reserve memory for fields.
- Java is class-based: every variable, method, and statement lives inside some class.
- Real-life analogy: an architect drawing of a house. It lists rooms, colour, and area, but you cannot live in the drawing.
public class Car {
// state (fields)
String brand;
String color;
int speed;
// behaviour (methods)
void start() {
System.out.println(brand + " started");
}
void accelerate(int by) {
speed += by;
System.out.println(brand + " speed = " + speed);
}
} Class & object — real-life blueprint vs real things
A class is the blueprint (house plan, car design, cookie cutter, admission form); an object is the real thing built from it, each with its own values. The diagram links four real-life examples to Java code and the stack / heap memory view.
- Class: declared once with
class; logical; no heap memory for fields. - Object: created with
new; lives on the heap; own state, shared behaviour. - Reference: the variable (
c1) holds the address, not the object itself. - No struct: Java has only classes — use a
recordfor struct-like data.
What is an object?
- An object is a real instance of a class, created at runtime with
new. It occupies heap memory and holds its own copy of every instance field. - One class can create any number of objects; each one has independent values.
- Real-life analogy: the actual houses built from one drawing. Each has its own address and colour, but all follow the same plan.
| Characteristic | Meaning | Car example |
|---|---|---|
| State | Data stored in fields | brand = "Toyota", speed = 80 |
| Behaviour | What it can do (methods) | start(), accelerate(20) |
| Identity | Unique existence in memory, even if values match | car1 != car2 although both are red Toyotas |
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car(); // object 1
car1.brand = "Toyota";
car1.color = "Red";
Car car2 = new Car(); // object 2
car2.brand = "Honda";
car2.color = "Blue";
car1.start(); // Toyota started
car2.accelerate(40); // Honda speed = 40
System.out.println(car1.speed); // 0 (independent state)
}
} Real-life examples of classes and objects
| Class (blueprint) | Objects (real things) | State (fields) | Behaviour (methods) |
|---|---|---|---|
| House plan | Your house, neighbour house | rooms, color, area | openDoor(), paint() |
| Car | car1 Toyota, car2 Honda | brand, color, speed | start(), brake(), accelerate() |
| Student | Asha, Ravi, Meena | name, roll, marks | study(), writeExam() |
| BankAccount | Account A001, A002 | accountNo, holder, balance | deposit(), withdraw() |
| Mobile | Your phone, my phone | model, battery, storage | call(), charge(), click() |
| Employee | Emp 101, Emp 102 | id, name, salary | work(), applyLeave() |
| Book | Java book, C book | title, author, price | open(), discount() |
| Cookie cutter (mould) | Each cookie | shape, topping | bake(), decorate() |
Differences between class and object
| Point | Class | Object |
|---|---|---|
| Meaning | Blueprint / template | Instance of the blueprint |
| Nature | Logical entity | Physical (runtime) entity |
| Created with | class keyword, once in source code | new keyword, many times at runtime |
| Memory | No heap memory for instance fields | Heap memory for its own fields |
| Count | Declared once | Any number of objects from one class |
| Loaded / created | Loaded by the class loader once | Created each time new runs |
| Example | class Car | car1, car2, car3 |
| Real life | House drawing | Actual houses |
Syntax of a class
- Only the
classkeyword, the name, and the braces are required. Everything else is optional.
| Part | Example | Purpose |
|---|---|---|
| Access modifier | public or none | Who can use the class |
| Other modifiers | final, abstract, sealed | Restrict inheritance or instantiation |
| Keyword and name | class Student | Name in PascalCase; must match the file if public |
| Superclass | extends Person | Inherit from one class (default Object) |
| Interfaces | implements Comparable<Student> | Promise to provide methods |
| Fields | private String name; | State of each object |
| Constructors | Student(String name) { ... } | Initialize a new object |
| Methods | void study() { ... } | Behaviour |
| Initializer blocks | { ... } and static { ... } | Extra setup code |
| Nested types | class Address { } inside | Helper classes, enums, records |
public class Student extends Object implements Comparable<Student> {
private String name; // field
private int marks; // field
static int count; // class-level field
Student(String name, int marks) { // constructor
this.name = name;
this.marks = marks;
count++;
}
void show() { // method
System.out.println(name + " : " + marks);
}
@Override
public int compareTo(Student other) {
return Integer.compare(marks, other.marks);
}
} Creating objects with new
Student s = new Student("Asha", 92);does four things: declares a reference variables, allocates heap memory, runs the constructor, and stores the object address ins.- Fields get default values before the constructor runs:
0,0.0,false, NUL character, ornull. - Local variables have no default; they must be assigned before use.
| Way to create an object | Example | Where used |
|---|---|---|
new keyword | new Student() | Everyday code (99% of cases) |
| Static factory method | List.of(1, 2), LocalDate.now() | Library APIs, caching, readable names |
clone() | arr.clone() | Copy arrays or Cloneable objects |
| Reflection | Student.class.getDeclaredConstructor().newInstance() | Frameworks such as Spring, JUnit |
| Deserialization | (Student) in.readObject() | Restoring saved objects |
Reference variables, stack, and heap
- The object lives in the heap. The variable (
s) lives on the stack (for locals) and holds only a reference to it. - Assigning one reference to another copies the address, not the object: both names now point to the same object.
- Setting a reference to
nulldisconnects it. When no reference reaches the object, the garbage collector can reclaim it.
public class RefDemo {
public static void main(String[] args) {
Car a = new Car();
a.brand = "Toyota";
Car b = a; // b points to the SAME object
b.brand = "Honda";
System.out.println(a.brand); // Honda
Car c = new Car(); // a different object
c.brand = "Honda";
System.out.println(a == b); // true (same object)
System.out.println(a == c); // false (different objects)
a = null; // object still reachable through b
b = null; // now eligible for garbage collection
}
}
// STACK HEAP
// a ----\
// >-----> [Car: brand=Honda]
// b ----/
// c -----------> [Car: brand=Honda] Members of a class
| Member | Belongs to | Example | Accessed as |
|---|---|---|---|
| Instance variable | Each object (own copy) | String name; | s.name |
| Static variable | The class (one shared copy) | static int count; | Student.count |
| Instance method | An object | void show() { } | s.show() |
| Static method | The class | static int total() { } | Student.total() |
| Constructor | Object creation | Student(String n) { } | new Student("Asha") |
| Instance initializer block | Each object creation | { id = nextId++; } | Runs before constructor body |
| Static initializer block | Class loading (once) | static { loadConfig(); } | Runs automatically |
| Nested / inner class | The class or an object | static class Address { } | new Student.Address() |
Differences between instance, static, and local variables
| Point | Instance variable | Static variable | Local variable |
|---|---|---|---|
| Declared | Inside class, outside methods | Inside class with static | Inside a method, constructor, or block |
| Copies | One per object | One per class | One per method call |
| Memory | Heap (inside the object) | Heap (class data area) | Stack frame |
| Default value | Yes (0, false, null) | Yes | No; must be assigned |
| Lifetime | While the object is reachable | While the class is loaded | Until the method returns |
| Access modifiers | Allowed | Allowed | Not allowed (only final) |
| Example | name, marks | count, SCHOOL_NAME | int total inside main |
Differences between structure and class
- A structure (
struct) in C groups related variables under one name. C++ extendedstructto be almost the same asclass. - Java has no
structkeyword. Every user-defined type is a class (or an interface, enum, or record). The closest Java feature to a struct is arecord(Java 16+).
| Point | Structure in C | Structure in C++ | Class in Java |
|---|---|---|---|
| Keyword | struct | struct | class (Java has no struct) |
| Contains | Data members only | Data members and functions | Fields, methods, constructors, blocks, nested types |
| Default access | Everything public (no access control) | public | Package-private (no modifier) |
| Data hiding / encapsulation | Not supported | Supported, but members default to public | Supported; fields usually private |
| Constructors / destructors | No | Yes | Constructors yes; no destructors (garbage collector) |
| Inheritance | Not supported | Supported (default public inheritance) | Single class inheritance with extends |
| Polymorphism | No | Yes (virtual functions) | Yes; all instance methods are virtual by default |
| Memory location | Stack or heap, value stored directly | Stack or heap, value stored directly | Objects always on the heap; variables hold references |
Assignment a = b | Copies all members | Copies all members | Copies the reference (both point to one object) |
Can be null | No (pointers can) | No (pointers can) | Yes |
| Typical use | Group plain data (records) | Plain data or small types | Full objects with state and behaviour |
| Closest Java equivalent | record | record or a small class | - |
Records: the Java answer to structures
- A
recordis a compact, immutable class for carrying data, like a C struct with safety built in. - The compiler generates a private final field, a constructor, accessors (
name()),equals,hashCode, andtoStringfor you. - Use a record for DTOs, API responses, map keys, and coordinates; use a normal class when objects need changing state or rich behaviour.
public class RecordDemo {
// C: struct Point { int x; int y; };
// Java: record (immutable data carrier)
record Point(int x, int y) {
double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}
public static void main(String[] args) {
Point p = new Point(3, 4);
Point q = new Point(3, 4);
System.out.println(p); // Point[x=3, y=4]
System.out.println(p.x() + ", " + p.y()); // 3, 4
System.out.println(p.equals(q)); // true (value equality generated)
System.out.println(p.distanceFromOrigin()); // 5.0
}
} Advanced — Classes & Objects
The Object class: root of every class
- If a class does not write
extends, it extendsjava.lang.Object. So every object has these methods.
| Method | Default behaviour | Override when |
|---|---|---|
toString() | Class name + @ + hash in hex | Always, for readable logs and debugging |
equals(Object o) | Same as == (identity) | Objects with equal values should be equal |
hashCode() | Identity-based number | Whenever you override equals |
getClass() | Runtime Class object | Final; cannot override |
clone() | Protected shallow copy (needs Cloneable) | Rarely; prefer copy constructors |
finalize() | Deprecated (Java 9) for removal | Never; use try-with-resources |
wait(), notify(), notifyAll() | Thread coordination | Final; used with synchronized |
Identity vs equality: overriding equals, hashCode, and toString
==on objects checks identity (same memory object).equalsshould check logical value.- If you override
equals, you must overridehashCodeso equal objects land in the sameHashMap/HashSetbucket. - Use
Objects.equalsandObjects.hashto write them safely, or let the IDE generate them.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Book {
private final String isbn;
private final String title;
Book(String isbn, String title) {
this.isbn = isbn;
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book other)) return false;
return isbn.equals(other.isbn);
}
@Override
public int hashCode() { return Objects.hash(isbn); }
@Override
public String toString() { return "Book[" + isbn + ", " + title + "]"; }
public static void main(String[] args) {
Book a = new Book("978-1", "Java Basics");
Book b = new Book("978-1", "Java Basics");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same ISBN)
Set<Book> shelf = new HashSet<>();
shelf.add(a);
shelf.add(b);
System.out.println(shelf.size()); // 1
System.out.println(a); // Book[978-1, Java Basics]
}
} Arrays of objects
new Student[3]creates an array of three references, allnull. It does not create anyStudentobjects.- Create each object separately, or you get
NullPointerExceptionwhen calling a method on an element.
public class StudentArray {
static class Student {
String name;
int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
}
public static void main(String[] args) {
Student[] cls = new Student[3]; // [null, null, null]
cls[0] = new Student("Asha", 92);
cls[1] = new Student("Ravi", 85);
cls[2] = new Student("Meena", 78);
Student top = cls[0];
int total = 0;
for (Student s : cls) {
total += s.marks;
if (s.marks > top.marks) top = s;
}
System.out.println("Average = " + total / (double) cls.length); // 85.0
System.out.println("Topper = " + top.name); // Asha
}
} Passing objects to methods
- Java is always pass-by-value. For objects, the value passed is the reference.
- So a method can change the object fields, and the caller sees the change.
- But reassigning the parameter (
acc = new Account()) inside the method does not affect the caller variable.
public class PassObject {
static class Account { double balance; }
static void addBonus(Account acc) {
acc.balance += 100; // visible to caller
}
static void replace(Account acc) {
acc = new Account(); // only the local parameter changes
acc.balance = 9999;
}
public static void main(String[] args) {
Account a = new Account();
addBonus(a);
replace(a);
System.out.println(a.balance); // 100.0
}
} Anonymous objects and method chaining
- An anonymous object is created and used without storing a reference:
new Car().start();. - It becomes eligible for garbage collection right after the statement.
- Methods that
return thisallow chaining, as inStringBuilderand builder classes.
public class Pizza {
private String size = "M";
private int toppings;
Pizza size(String s) { this.size = s; return this; }
Pizza addTopping() { toppings++; return this; }
void order() { System.out.println(size + " pizza with " + toppings + " toppings"); }
public static void main(String[] args) {
new Pizza().size("L").addTopping().addTopping().order(); // L pizza with 2 toppings
}
} Object lifecycle
| Stage | What happens | Code trigger |
|---|---|---|
| Class loading | JVM loads the class and runs static blocks once | First use of the class |
| Allocation | Heap memory reserved, fields set to defaults | new |
| Initialization | Field initializers, instance blocks, constructor run | Constructor call |
| In use | Methods called through references | obj.method() |
| Unreachable | No live reference points to the object | obj = null, scope ends |
| Garbage collection | JVM reclaims the memory at some later time | Automatic; System.gc() is only a hint |
Designing good classes
- One class, one responsibility:
Studentholds student data; a separateReportPrinterprints reports. - Keep fields
privateand expose behaviour through methods (encapsulation, next lessons). - Validate in the constructor so an object is never created in an invalid state.
- Prefer immutable classes (
finalfields, no setters) or records for values like money, dates, and coordinates. - Name classes as nouns (
Invoice,Customer) and methods as verbs (calculateTotal,send).
Tricky Interview Points
Q1) What is a class?
Answer A user-defined type and blueprint that declares the state (fields) and behaviour (methods) its objects will have. It is a logical entity and does not hold object data itself.
Q2) What is an object?
Answer A runtime instance of a class, created with new, stored on the heap, with its own state, behaviour from the class methods, and a unique identity.
Q3) Give a real-life example of class and object.
Answer A house plan is a class; the actual houses built from it are objects. Car is a class; your Toyota and my Honda are objects with their own brand, colour, and speed.
Q4) Difference between class and object?
Answer A class is a blueprint declared once with the class keyword and is a logical entity. Objects are physical instances created many times with new and occupy heap memory.
Q5) Does Java have structures (struct)?
Answer No. Java has no struct keyword. All user-defined types are classes, interfaces, enums, or records. A record is the closest equivalent to a C struct.
Q6) Difference between a C++ struct and a Java class?
Answer A C++ struct defaults to public members and is stored by value (assignment copies all members). A Java class defaults to package-private, its objects always live on the heap, and assignment copies only the reference.
Q7) What does the new keyword do?
Answer Allocates heap memory, sets fields to default values, runs initializers and the constructor, and returns the reference to the new object.
Q8) Where are objects and reference variables stored?
Answer Objects are always on the heap. Local reference variables are on the stack; fields that hold references are inside their owning object on the heap.
Q9) Can two references point to one object? What happens on change?
Answer Yes. Assignment copies the reference, so a change made through one reference is visible through the other.
Q10) What are the ways to create an object in Java?
Answer new, static factory methods, clone(), reflection (Constructor.newInstance), and deserialization.
Q11) What is the default value of instance variables?
Answer 0 for numeric types, false for boolean, the NUL character for char, and null for references. Local variables have no default.
Q12) Instance variable vs static variable?
Answer Each object has its own copy of an instance variable. A static variable has a single copy shared by all objects of the class.
Q13) What is the root class of all Java classes?
Answer java.lang.Object. It provides toString, equals, hashCode, getClass, clone, wait, notify, and notifyAll.
Q14) == vs equals for objects?
Answer == compares references (same object). equals compares logical value if the class overrides it; otherwise it behaves like ==.
Q15) Why override hashCode when overriding equals?
Answer The contract requires equal objects to have equal hash codes. Otherwise HashMap and HashSet will treat equal objects as different keys.
Q16) Does new Student[5] create five Student objects?
Answer No. It creates an array of five null references. Each element must be assigned new Student(...) separately.
Q17) What is an anonymous object?
Answer An object created without storing its reference, such as new Car().start(). It is eligible for garbage collection right after use.
Q18) When is an object eligible for garbage collection?
Answer When no live thread can reach it through any chain of references, for example after all references are set to null or go out of scope.
Simple Programs
Student class with multiple objects
public class Student {
String name;
int roll;
double marks;
void display() {
System.out.println(roll + " " + name + " " + marks + " " + grade());
}
char grade() {
if (marks >= 90) return 'A';
if (marks >= 75) return 'B';
if (marks >= 60) return 'C';
return 'D';
}
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Asha"; s1.roll = 101; s1.marks = 92;
Student s2 = new Student();
s2.name = "Ravi"; s2.roll = 102; s2.marks = 74;
s1.display(); // 101 Asha 92.0 A
s2.display(); // 102 Ravi 74.0 C
}
} Bank account: deposit, withdraw, and balance
public class BankAccount {
private final String accountNo;
private final String holder;
private double balance;
BankAccount(String accountNo, String holder, double opening) {
if (opening < 0) throw new IllegalArgumentException("opening balance cannot be negative");
this.accountNo = accountNo;
this.holder = holder;
this.balance = opening;
}
void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amt;
}
boolean withdraw(double amt) {
if (amt > balance) {
System.out.println("Insufficient balance for " + holder);
return false;
}
balance -= amt;
return true;
}
@Override
public String toString() {
return accountNo + " | " + holder + " | Rs." + balance;
}
public static void main(String[] args) {
BankAccount a = new BankAccount("A001", "Ravi", 5000);
BankAccount b = new BankAccount("A002", "Priya", 8500);
a.deposit(1500);
b.withdraw(10000); // Insufficient balance for Priya
System.out.println(a); // A001 | Ravi | Rs.6500.0
System.out.println(b); // A002 | Priya | Rs.8500.0
}
} Rectangle: area and perimeter for many objects
public class Rectangle {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double area() { return length * width; }
double perimeter() { return 2 * (length + width); }
public static void main(String[] args) {
Rectangle[] rects = { new Rectangle(4, 5), new Rectangle(2.5, 3), new Rectangle(10, 1) };
Rectangle biggest = rects[0];
for (Rectangle r : rects) {
System.out.printf("%.1f x %.1f -> area %.2f, perimeter %.2f%n",
r.length, r.width, r.area(), r.perimeter());
if (r.area() > biggest.area()) biggest = r;
}
System.out.println("Largest area = " + biggest.area());
}
} Counting objects with a static variable
public class Visitor {
static int count = 0; // shared by all objects
final int ticketNo; // own copy per object
final String name;
Visitor(String name) {
this.name = name;
count++;
ticketNo = count;
}
public static void main(String[] args) {
Visitor v1 = new Visitor("Anu");
Visitor v2 = new Visitor("Bala");
Visitor v3 = new Visitor("Chitra");
System.out.println(v3.name + " has ticket " + v3.ticketNo); // Chitra has ticket 3
System.out.println("Total visitors = " + Visitor.count); // 3
}
} Reference aliasing vs copying an object
public class CopyDemo {
static class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point(Point other) { this(other.x, other.y); } // copy constructor
public String toString() { return "(" + x + ", " + y + ")"; }
}
public static void main(String[] args) {
Point original = new Point(1, 2);
Point alias = original; // same object
Point copy = new Point(original); // new object with same values
alias.x = 100;
System.out.println(original); // (100, 2) changed through alias
System.out.println(copy); // (1, 2) independent copy
}
} Struct-style data with a record vs a full class
public class RecordVsClass {
// data only: record (like a C struct, but immutable)
record Product(String name, double price) { }
// data + changing state + rules: class
static class Cart {
private double total;
private int items;
void add(Product p, int qty) {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive");
total += p.price() * qty;
items += qty;
}
@Override
public String toString() { return items + " items, total Rs." + total; }
}
public static void main(String[] args) {
Product pen = new Product("Pen", 20);
Product book = new Product("Notebook", 55);
Cart cart = new Cart();
cart.add(pen, 3);
cart.add(book, 2);
System.out.println(pen); // Product[name=Pen, price=20.0]
System.out.println(cart); // 5 items, total Rs.170.0
}
} Library: array of Book objects with search
public class Library {
static class Book {
String title, author;
int year;
Book(String title, String author, int year) {
this.title = title; this.author = author; this.year = year;
}
public String toString() { return title + " by " + author + " (" + year + ")"; }
}
public static void main(String[] args) {
Book[] books = {
new Book("Effective Java", "Bloch", 2018),
new Book("Head First Java", "Sierra", 2022),
new Book("Clean Code", "Martin", 2008)
};
String search = "java";
for (Book b : books) {
if (b.title.toLowerCase().contains(search)) System.out.println(b);
}
}
} Problem Solving Tricks
- Remember: class = blueprint (written once), object = real thing (created with
new, many times). - If you can point at it and it has its own values, it is an object; if it describes many such things, it is a class.
- Name classes as nouns in PascalCase (
BankAccount) and objects / variables in camelCase (savingsAccount). - Override
toStringearly; printing objects becomes readable for debugging. - Always override
equalsandhashCodetogether, or neither. new Student[3]gives threenullslots; create eachStudentbefore using it.b = acopies the reference, not the object. Use a copy constructor for a real copy.- Make fields
privatefrom the very first class so encapsulation becomes a habit. - For pure data (like a C struct), use a
recordinstead of writing fields, getters, equals, and hashCode by hand. - One class, one responsibility: a
Studentshould not also read files and send email.
Practice Programs List
- Create a
Carclass with brand, color, and speed, plusstart(),accelerate(), andbrake(). Create three car objects. - Create a
Studentclass and an array of five students; print the topper and class average. - Model a
BankAccountwith deposit and withdraw that refuses overdrafts. - Write a
Bookclass with adiscountedPrice(double percent)method and a customtoString. - Assign
Book copy = original;, changecopy.price, and explain whyoriginalalso changes. Then write a copy constructor. - Add a static counter that counts how many objects of a class were created.
- Write a
Pointclass withdistanceTo(Point other)and test it with three points. - Rewrite
Pointas arecordand compare the amount of code. - Override
equalsandhashCodein anEmployeeclass by employee id and test with aHashSet. - Create a
Mobileclass from real life with at least four fields and three methods. - Write a program that shows
==vsequalsfor two objects with the same values. - Pass an object to a method that changes a field, and another method that reassigns the parameter. Print the results and explain.
- List five real-life class and object pairs from your college or workplace and model one of them in Java.
- Write a table in comments comparing a C struct, a C++ struct, and your Java class for one example (such as
Student).