← Java roadmap

Topic 6 of 30 · Intermediate

Classes, Objects & Constructors

Blueprints, instances, this, static and records.

Concept

A class is a blueprint with fields (state) and methods (behaviour). new creates an object on the heap and runs a constructor.

this refers to the current object. Constructors can chain with this(...). static members belong to the class, shared by all objects.

Records (Java 16+) are concise immutable data classes that auto-generate the constructor, getters, equals, hashCode and toString.

Code (Java 21)

class Student {
    private final String name;
    private double cgpa;
    static int count = 0;

    Student(String name, double cgpa) {
        this.name = name;
        this.cgpa = cgpa;
        count++;
    }
    Student(String name) { this(name, 0.0); }

    String getName() { return name; }
}

record Offer(String company, double ctc) {}

Offer o = new Offer("TCS", 7.0);
System.out.println(o.company());

Remember

  • No constructor written → a default no-arg one is added.
  • static = per class; instance = per object.
  • Use records for plain data carriers.

Interview questions

Can a constructor be private?

Yes — used in singletons and factory/utility classes to control object creation.

Difference between static and instance variables?

A static variable has one copy shared by all objects; each object has its own copy of instance variables.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Classes, Objects & Constructors” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.