Skip to main content

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.

L1

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.

Java class and object infographic with real-life examples: a house blueprint creating three houses, a Car class creating Toyota, Honda, and Tata cars, a cookie cutter and cookies, a Student form and three student cards, Java code with stack and heap memory, and a class vs object comparison table.
Java class & object — the class says what it is, each object is a real instance with its own values
  • 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 record for 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.
CharacteristicMeaningCar example
StateData stored in fieldsbrand = "Toyota", speed = 80
BehaviourWhat it can do (methods)start(), accelerate(20)
IdentityUnique existence in memory, even if values matchcar1 != 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 planYour house, neighbour houserooms, color, areaopenDoor(), paint()
Carcar1 Toyota, car2 Hondabrand, color, speedstart(), brake(), accelerate()
StudentAsha, Ravi, Meenaname, roll, marksstudy(), writeExam()
BankAccountAccount A001, A002accountNo, holder, balancedeposit(), withdraw()
MobileYour phone, my phonemodel, battery, storagecall(), charge(), click()
EmployeeEmp 101, Emp 102id, name, salarywork(), applyLeave()
BookJava book, C booktitle, author, priceopen(), discount()
Cookie cutter (mould)Each cookieshape, toppingbake(), decorate()

Differences between class and object

PointClassObject
MeaningBlueprint / templateInstance of the blueprint
NatureLogical entityPhysical (runtime) entity
Created withclass keyword, once in source codenew keyword, many times at runtime
MemoryNo heap memory for instance fieldsHeap memory for its own fields
CountDeclared onceAny number of objects from one class
Loaded / createdLoaded by the class loader onceCreated each time new runs
Exampleclass Carcar1, car2, car3
Real lifeHouse drawingActual houses

Syntax of a class

  • Only the class keyword, the name, and the braces are required. Everything else is optional.
PartExamplePurpose
Access modifierpublic or noneWho can use the class
Other modifiersfinal, abstract, sealedRestrict inheritance or instantiation
Keyword and nameclass StudentName in PascalCase; must match the file if public
Superclassextends PersonInherit from one class (default Object)
Interfacesimplements Comparable<Student>Promise to provide methods
Fieldsprivate String name;State of each object
ConstructorsStudent(String name) { ... }Initialize a new object
Methodsvoid study() { ... }Behaviour
Initializer blocks{ ... } and static { ... }Extra setup code
Nested typesclass Address { } insideHelper 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 variable s, allocates heap memory, runs the constructor, and stores the object address in s.
  • Fields get default values before the constructor runs: 0, 0.0, false, NUL character, or null.
  • Local variables have no default; they must be assigned before use.
Way to create an objectExampleWhere used
new keywordnew Student()Everyday code (99% of cases)
Static factory methodList.of(1, 2), LocalDate.now()Library APIs, caching, readable names
clone()arr.clone()Copy arrays or Cloneable objects
ReflectionStudent.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 null disconnects 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

MemberBelongs toExampleAccessed as
Instance variableEach object (own copy)String name;s.name
Static variableThe class (one shared copy)static int count;Student.count
Instance methodAn objectvoid show() { }s.show()
Static methodThe classstatic int total() { }Student.total()
ConstructorObject creationStudent(String n) { }new Student("Asha")
Instance initializer blockEach object creation{ id = nextId++; }Runs before constructor body
Static initializer blockClass loading (once)static { loadConfig(); }Runs automatically
Nested / inner classThe class or an objectstatic class Address { }new Student.Address()

Differences between instance, static, and local variables

PointInstance variableStatic variableLocal variable
DeclaredInside class, outside methodsInside class with staticInside a method, constructor, or block
CopiesOne per objectOne per classOne per method call
MemoryHeap (inside the object)Heap (class data area)Stack frame
Default valueYes (0, false, null)YesNo; must be assigned
LifetimeWhile the object is reachableWhile the class is loadedUntil the method returns
Access modifiersAllowedAllowedNot allowed (only final)
Examplename, markscount, SCHOOL_NAMEint total inside main

Differences between structure and class

  • A structure (struct) in C groups related variables under one name. C++ extended struct to be almost the same as class.
  • Java has no struct keyword. Every user-defined type is a class (or an interface, enum, or record). The closest Java feature to a struct is a record (Java 16+).
PointStructure in CStructure in C++Class in Java
Keywordstructstructclass (Java has no struct)
ContainsData members onlyData members and functionsFields, methods, constructors, blocks, nested types
Default accessEverything public (no access control)publicPackage-private (no modifier)
Data hiding / encapsulationNot supportedSupported, but members default to publicSupported; fields usually private
Constructors / destructorsNoYesConstructors yes; no destructors (garbage collector)
InheritanceNot supportedSupported (default public inheritance)Single class inheritance with extends
PolymorphismNoYes (virtual functions)Yes; all instance methods are virtual by default
Memory locationStack or heap, value stored directlyStack or heap, value stored directlyObjects always on the heap; variables hold references
Assignment a = bCopies all membersCopies all membersCopies the reference (both point to one object)
Can be nullNo (pointers can)No (pointers can)Yes
Typical useGroup plain data (records)Plain data or small typesFull objects with state and behaviour
Closest Java equivalentrecordrecord or a small class-

Records: the Java answer to structures

  • A record is 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, and toString for 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
    }
}
L2

Advanced — Classes & Objects

The Object class: root of every class

  • If a class does not write extends, it extends java.lang.Object. So every object has these methods.
MethodDefault behaviourOverride when
toString()Class name + @ + hash in hexAlways, for readable logs and debugging
equals(Object o)Same as == (identity)Objects with equal values should be equal
hashCode()Identity-based numberWhenever you override equals
getClass()Runtime Class objectFinal; cannot override
clone()Protected shallow copy (needs Cloneable)Rarely; prefer copy constructors
finalize()Deprecated (Java 9) for removalNever; use try-with-resources
wait(), notify(), notifyAll()Thread coordinationFinal; used with synchronized

Identity vs equality: overriding equals, hashCode, and toString

  • == on objects checks identity (same memory object). equals should check logical value.
  • If you override equals, you must override hashCode so equal objects land in the same HashMap / HashSet bucket.
  • Use Objects.equals and Objects.hash to 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, all null. It does not create any Student objects.
  • Create each object separately, or you get NullPointerException when 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 this allow chaining, as in StringBuilder and 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

StageWhat happensCode trigger
Class loadingJVM loads the class and runs static blocks onceFirst use of the class
AllocationHeap memory reserved, fields set to defaultsnew
InitializationField initializers, instance blocks, constructor runConstructor call
In useMethods called through referencesobj.method()
UnreachableNo live reference points to the objectobj = null, scope ends
Garbage collectionJVM reclaims the memory at some later timeAutomatic; System.gc() is only a hint

Designing good classes

  • One class, one responsibility: Student holds student data; a separate ReportPrinter prints reports.
  • Keep fields private and expose behaviour through methods (encapsulation, next lessons).
  • Validate in the constructor so an object is never created in an invalid state.
  • Prefer immutable classes (final fields, no setters) or records for values like money, dates, and coordinates.
  • Name classes as nouns (Invoice, Customer) and methods as verbs (calculateTotal, send).
L3

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.

L4

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);
        }
    }
}
L5

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 toString early; printing objects becomes readable for debugging.
  • Always override equals and hashCode together, or neither.
  • new Student[3] gives three null slots; create each Student before using it.
  • b = a copies the reference, not the object. Use a copy constructor for a real copy.
  • Make fields private from the very first class so encapsulation becomes a habit.
  • For pure data (like a C struct), use a record instead of writing fields, getters, equals, and hashCode by hand.
  • One class, one responsibility: a Student should not also read files and send email.
L6

Practice Programs List

  1. Create a Car class with brand, color, and speed, plus start(), accelerate(), and brake(). Create three car objects.
  2. Create a Student class and an array of five students; print the topper and class average.
  3. Model a BankAccount with deposit and withdraw that refuses overdrafts.
  4. Write a Book class with a discountedPrice(double percent) method and a custom toString.
  5. Assign Book copy = original;, change copy.price, and explain why original also changes. Then write a copy constructor.
  6. Add a static counter that counts how many objects of a class were created.
  7. Write a Point class with distanceTo(Point other) and test it with three points.
  8. Rewrite Point as a record and compare the amount of code.
  9. Override equals and hashCode in an Employee class by employee id and test with a HashSet.
  10. Create a Mobile class from real life with at least four fields and three methods.
  11. Write a program that shows == vs equals for two objects with the same values.
  12. Pass an object to a method that changes a field, and another method that reassigns the parameter. Print the results and explain.
  13. List five real-life class and object pairs from your college or workplace and model one of them in Java.
  14. Write a table in comments comparing a C struct, a C++ struct, and your Java class for one example (such as Student).