Lesson 1 of 12 · 10 min · Object-oriented Java

Classes, objects, records and interfaces

Covers: Java 25 LTS (also valid on 21). Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • What a class and an object are, and how new creates one
  • Fields, methods, constructors, this and static
  • Interfaces, default methods and abstract classes: when to use each
  • Records for plain data
  • How to run a first Java file

In simple words

A class is a blueprint, like the plan for a house. An object is one actual house built from that plan. The blueprint says what every house has (rooms, a door) and what it can do (open the door). Each object keeps its own values: two houses from one plan can be painted differently. An interface is a promise about what something can do, without saying how.

Words to know

  • Class: a blueprint that defines fields (data) and methods (behaviour).
  • Object: one instance created from a class with new.
  • Constructor: special code that runs when an object is created.
  • Interface: a contract listing methods a class agrees to provide.

Your first class

public class Customer {
    private final String name;      // field: each object has its own copy
    private final String city;

    public Customer(String name, String city) {     // constructor
        this.name = name;
        this.city = city;
    }

    public String describe() {                      // method
        return name + " from " + city;
    }

    public static void main(String[] args) {
        Customer asha = new Customer("Asha", "Hyderabad");
        System.out.println(asha.describe());        // Asha from Hyderabad
    }
}

Compile and run (JDK installed):

javac Customer.java
java Customer

Since Java 11 you can run a single file directly with java Customer.java. In Java 25, a file can also use an instance main method with no public static and no class wrapper for small programs, but real projects still use the explicit form above.

Key points:

  • new allocates an object on the heap and runs the constructor. The variable asha holds a reference to it.
  • this is the current object. Use it to tell a field from a parameter of the same name.
  • If you write no constructor, Java gives a default no-argument constructor; once you write any constructor, it does not.
  • You can have several constructors with different parameters (overloading), and one can call another with this(...).
  • File and class name must match for a public class.

Instance versus static

  • Instance members belong to each object (name, describe()).
  • static members belong to the class itself and are shared: a counter, a constant, a utility method.
public class Prices {
    public static final double GST_RATE = 0.18;           // constant

    public static double withGst(double price) {          // utility method, no object needed
        return price * (1 + GST_RATE);
    }
}
// usage: Prices.withGst(1000)  ->  1180.0

A static method cannot use instance fields (there is no this). Avoid mutable static state; it makes code hard to test and unsafe with threads.

Interfaces

An interface declares what a type can do. Classes implement it and may implement several:

public interface PaymentMethod {
    boolean pay(double amount);

    default String label() {                  // default method: optional shared behaviour
        return "payment";
    }

    static PaymentMethod cash() {             // static method on an interface
        return amount -> true;
    }
}

public class UpiPayment implements PaymentMethod {
    @Override
    public boolean pay(double amount) {
        System.out.println("Paid " + amount + " by UPI");
        return true;
    }
}
  • Methods are public abstract by default; fields are public static final.
  • default methods (Java 8) let you add behaviour to an interface without breaking existing implementers.
  • An interface with one abstract method is a functional interface, which a lambda can implement (amount -> true); the streams lesson builds on this.
  • Code to the interface: PaymentMethod p = new UpiPayment(); lets you swap implementations (tests, new payment types) without changing callers.

Abstract classes

An abstract class can hold state and partial implementation, and cannot be instantiated:

public abstract class Report {
    private final String title;
    protected Report(String title) { this.title = title; }

    public final String render() {            // template method
        return "== " + title + " ==\n" + body();
    }
    protected abstract String body();         // subclasses must provide this
}
Interface Abstract class
Multiple inheritance a class can implement many a class extends only one
State (instance fields) no yes
Constructors no yes
Use when defining a capability or contract sharing code and state among closely related classes

Rule of thumb: start with an interface; use an abstract class only when subclasses really share fields and logic.

Records: data without boilerplate

A record (Java 16) is a short way to write an immutable data carrier:

public record Order(int id, String customer, double amount) {
    public Order {                                    // compact constructor for validation
        if (amount < 0) throw new IllegalArgumentException("amount must be >= 0");
    }
    public boolean isLarge() { return amount >= 1000; }
}

Order o = new Order(101, "Asha", 1200);
System.out.println(o.amount());     // 1200.0   (accessor, not getAmount())
System.out.println(o);              // Order[id=101, customer=Asha, amount=1200.0]

The compiler generates the constructor, accessors, equals, hashCode and toString. Fields are final. Records can implement interfaces but cannot extend classes. Use them for DTOs, API responses and keys in maps.

The Object class and toString

Every class extends java.lang.Object, so every object has toString(), equals(), hashCode() and getClass(). Override toString() to get readable logs: without it you see Customer@1b6d3586.

Other building blocks

  • Enums for a fixed set of values: enum Status { PAID, PENDING, REFUNDED }, which can also have fields and methods.
  • Packages group classes (package com.shop.orders;); imports bring other packages' classes in.
  • Nested classes (static nested, inner, local, anonymous) exist; prefer small top-level classes and lambdas.
  • var (Java 10) lets the compiler infer a local variable's type: var list = new ArrayList<String>();.

Common mistakes

  • Making everything static, which turns object-oriented code into global functions and makes tests hard.
  • Exposing fields as public (the next lessons cover encapsulation).
  • Comparing objects with == instead of equals (it compares references).
  • Forgetting @Override, so a typo creates a new method instead of overriding.
  • Using an abstract class where an interface would do.

Try it yourself

  1. Write a Customer class with a constructor and describe() and run it from the command line.
  2. Make an interface Discount with double apply(double price) and two implementations; call them through the interface type.
  3. Rewrite your Customer as a record and compare the code and printed output.
  4. Add a static counter that tracks how many Customer objects have been created, then explain why mutable static state is risky.

Check yourself

What is the difference between a class and an object?

A class is the blueprint; an object is a specific instance of it created with new, holding its own field values.

When would you pick an interface over an abstract class?

When you only need to define a capability or contract, or a class needs several of them. Use an abstract class when subclasses share state and implementation.

What does a record generate automatically?

The canonical constructor, accessor methods, equals, hashCode and toString, with final fields.

What is a default method in an interface?

A method with a body inside an interface, giving implementers a default behaviour they can override.

Interview questions

What is the difference between an abstract class and an interface in Java?

An interface defines a contract (abstract methods plus default and static methods, constants only) and a class can implement many. An abstract class can have instance state, constructors and any method types, but a class can extend only one. Use interfaces for capabilities and abstract classes for shared base behaviour.

What is static and when would you use it?

A static member belongs to the class, not to an instance: constants, utility methods and factory methods. It cannot access instance members directly. Mutable static state should be avoided.

What are records and when do you use them?

Concise immutable data classes (Java 16+). Use them for DTOs, value objects and map keys where identity is defined by data, not by object identity.

Summary

  • A class is a blueprint; objects are created with new and hold their own state; constructors set it up.
  • static members belong to the class; avoid mutable static state.
  • Interfaces define contracts (with default methods); abstract classes share state and code; prefer interfaces.
  • Records give immutable data classes with generated equals, hashCode and toString.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.