InfoparkDailyCAREER TOOLS

Java · Lesson 6 of 9

Classes & objects

Fields, constructors, this, encapsulation with getters, and records.

A class is a blueprint; an object is an instance created with new.

  • Fields hold an object's data; methods define its behaviour.
  • A constructor has the class's name and no return type; it sets up the new object. this refers to the current object.
  • Encapsulation: make fields private and expose controlled access through public methods (getters, or methods that validate changes).
  • toString() controls how an object prints.

For simple data carriers, Java 16+ records generate the constructor, getters, equals, hashCode and toString for you: record Job(String title, double lpa) {}.

Example program

Run with JDK 17+: java Main.java
public class Main {
    static class Candidate {
        private final String name;
        private int experience;

        Candidate(String name, int experience) {
            this.name = name;
            this.experience = experience;
        }

        String getName() { return name; }

        void addYear() { experience++; }

        boolean isSenior() { return experience >= 5; }

        @Override
        public String toString() {
            return name + " (" + experience + " yrs)";
        }
    }

    record Job(String title, double lpa) {}

    public static void main(String[] args) {
        Candidate c = new Candidate("Meera", 4);
        c.addYear();
        System.out.println(c + " senior? " + c.isSenior());

        Job job = new Job("Backend Developer", 9.5);
        System.out.println(job);
        System.out.println(job.title());
    }
}

Output

Meera (5 yrs) senior? true
Job[title=Backend Developer, lpa=9.5]
Backend Developer

Save the code as Main.java and run java Main.java (JDK 11+ runs single files directly). Names and figures are fictional.

Key points

  • new creates an object from a class.
  • Private fields + public methods = encapsulation.
  • Records are concise immutable data classes.

Quick check

What does a constructor do?

Practice task

Create a BankAccount class with a private balance, deposit() and withdraw() methods, and refuse withdrawals larger than the balance.

Interview corner

What are the four pillars of OOP?

Encapsulation, inheritance, polymorphism and abstraction.

Why override equals() and hashCode() together?

Hash-based collections use hashCode to find a bucket and equals to compare. Equal objects must have equal hash codes, or HashMap/HashSet lookups break.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.