Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Java Classes, Interfaces, and Records for TypeScript Developers

This lesson is built with resources from youtube.com, triplet.fi and 1 more site.

Hello! Welcome back.

In our last lesson, we explored Java's type system, drawing a clear line between fast, stack-allocated primitive types (int, boolean) and flexible, heap-allocated reference types (String, Integer). You learned that reference variables are essentially pointers to objects in memory.

Today, we move from using Java's built-in reference types to defining our own. This is where object-oriented programming truly begins. We'll learn how to create blueprints for the core entities of our blog platform—like users and posts—using Java's class, interface, and record constructs. For each concept, we'll map it directly back to your deep experience with TypeScript, highlighting the crucial similarities and differences.

Our goal for this lesson is to learn how to define classes, interfaces, and records in Java, mapping their concepts of properties and methods from TypeScript.


1. The class: A Blueprint for Objects

Just like in TypeScript, a class in Java is a blueprint for creating objects. It bundles together state (data, called fields or instance variables) and behavior (actions, called methods).

Let's model a User for our blog. In TypeScript, you might write:

// TypeScript User class
class User {
  id: number;
  username: string;
  email: string;

  constructor(id: number, username: string, email: string) {
    this.id = id;
    this.username = username;
    this.email = email;
  }

  getProfileSummary(): string {
    return `User: ${this.username} (${this.email})`;
  }
}

The Java equivalent is strikingly similar, but more explicit about visibility.

// Java User class
public class User {
    // Fields (state)
    private Long id;
    private String username;
    private String email;

    // Constructor
    public User(Long id, String username, String email) {
        this.id = id;
        this.username = username;
        this.email = email;
    }

    // Method (behavior)
    public String getProfileSummary() {
        return "User: " + this.username + " (" + this.email + ")";
    }

    // Getters to access private fields
    public Long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getEmail() {
        return email;
    }
}

MERN-to-Java Mapping: Key Differences

  • Access Modifiers (public, private): This is a major concept in Java.
    • public: Accessible from anywhere.
    • private: Accessible only within this class.
    • It's a strong convention in Java to make all fields private and expose them through public methods (like getUsername()), a principle called encapsulation. In TypeScript, private exists but is often a compile-time check, whereas in Java, it's enforced by the runtime.
  • Getters/Setters: Because fields are private, we create public methods to get (get...) or change (set...) their values. In our example, we only have getters, making our User object partially immutable after creation (you can't change its fields from the outside).
  • Type Explicitness: Every field, method parameter, and return value must have an explicit type, which you're already familiar with from the previous lesson.


2. The interface: The Contract

An interface in Java defines a contract. It specifies a set of methods that a class must implement if it agrees to that contract. This is one of the most powerful tools for building flexible and decoupled systems.

Imagine we want different things in our system to be "publishable"—a blog post, a comment, a page. They all share the concept of having content that can be retrieved for display.

public interface Publishable {
    String getAuthor();
    String getContent();
    // In Java 8+, you can have default implementations
    default String getShortDescription() {
        if (getContent() == null) {
            return "";
        }
        return getContent().substring(0, Math.min(getContent().length(), 50)) + "...";
    }
}

Now, any class can promise to fulfill this contract by using the implements keyword.

public class Post implements Publishable {
    private String author;
    private String title;
    private String body;

    // ... constructor ...

    @Override // This annotation is optional but good practice
    public String getAuthor() {
        return this.author;
    }

    @Override
    public String getContent() {
        return this.body;
    }
    
    // ... other Post-specific methods ...
}
Java Interfaces: Duck and Frog Example
Just as a `Duck` can implement multiple behaviors like `Flyable` and `Swimmable`, our `Post` class can implement the `Publishable` contract, guaranteeing it provides the required methods.

MERN-to-Java Mapping: Nominal vs. Structural Typing

This is the most critical difference you need to grasp.

  • TypeScript uses Structural Typing: An object is compatible with an interface if it has the same shape (the right properties and methods). You don't need to explicitly say implements.
  • Java uses Nominal Typing: A class is compatible with an interface only if it explicitly declares that it implements that interface. The name matters.

This article gives an excellent explanation of this fundamental difference.

Type System Differences in TypeScript VS C# & Java

The article 'Type System Differences in TypeScript (Structural Type System) VS C# & Java (Nominal Type System)' explains the core philosophical difference between how TypeScript and Java check type compatibility. The examples use C#, but the principles are identical for Java.

Read the sections 'Nomen est omen', 'Structural typing', and 'Conclusion'. This will clarify why Java's implements keyword is so important and how it differs from your experience in TypeScript.

To see interfaces in action and learn about some newer features like default and static methods, this video provides a great hands-on tutorial.

Java Interface Tutorial

The video 'Java Interface Tutorial' walks through creating and implementing interfaces, showing how they enforce contracts and enable polymorphism.

Watch these key segments: 0:00 - 02:54: Covers the core concept of what an interface is and the syntax for a class to implement it. 10:24 - 12:12: Explains default methods, which allow you to add new methods to interfaces without breaking existing implementing classes—a very useful feature.



3. The record: The Immutable Data Carrier

A very common use case for a class is to simply hold data, like a response from an API or a Data Transfer Object (DTO). In the past, this required writing a lot of boilerplate code: a constructor, private fields, getters for each field, and correctly implemented equals(), hashCode(), and toString() methods.

Java 16 introduced records to solve this. A record is a special, concise form of a class designed for creating immutable data--only objects.

Let's revisit our User class. If its only purpose was to carry data, look at the difference.

The old way (as a class):

// ~30 lines of code
public final class UserData { // 'final' means it can't be extended
    private final Long id;
    private final String username;

    public UserData(Long id, String username) {
        this.id = id;
        this.username = username;
    }

    public Long getId() { return id; }
    public String getUsername() { return username; }

    @Override
    public boolean equals(Object o) { /*... boilerplate ...*/ }
    @Override
    public int hashCode() { /*... boilerplate ...*/ }
    @Override
    public String toString() { /*... boilerplate ...*/ }
}

The new way (as a record):

// 1 line of code!
public record UserData(Long id, String username) {}

That one line of code gives you all of this for free:

  • private final fields for id and username.
  • A public constructor that takes all the fields.
  • public getter methods for each field (e.g., id(), username()). Note the lack of get prefix.
  • Correct equals(), hashCode(), and toString() implementations.

This video is the perfect guide to understanding why records are so useful.

Records In Java - Full Tutorial - The Best New Java Feature You're Not Using

The video 'Records In Java - Full Tutorial' by Coding with John does an exceptional job of motivating why records exist by first showing the pain of writing a traditional data class, and then revealing how a record solves it.

Watch from 0:57 to 8:03. This covers: The boilerplate required for a traditional data class. The one-line record equivalent. A breakdown of what the record generates for you automatically. The core feature: immutability.

MERN-to-Java Mapping

A Java record is the closest equivalent to a simple, immutable data structure in TypeScript/JavaScript. It's conceptually similar to:

  • A TypeScript type alias for an object literal: type UserData = { id: number; username: string; }.
  • A JavaScript object created with Object.freeze().

You'll find records incredibly useful for defining DTOs, which act as the contract for your REST APIs.

Comparison of Classes and Records in Java
This table summarizes the key differences. The main takeaway is to use a `class` when you need complex behavior and mutable state, and a `record` when you need a simple, immutable data holder.


4. Hands-On: Modeling Our Domain

Let's put this all together. Inside your src/main/java/com/blogplatform directory:

  1. Create a User.java file and define a User class. It should have fields for id, username, and email, a constructor, and public getters.

    package com.blogplatform;
    
    public class User {
        private final Long id;
        private final String username;
        private final String email;
    
        public User(Long id, String username, String email) {
            this.id = id;
            this.username = username;
            this.email = email;
        }
    
        public Long getId() { return id; }
        public String getUsername() { return username; }
        public String getEmail() { return email; }
    }
    
  2. Create a Post.java file for a Post record. This is a great use case for a record since a post's core data (ID, title, content, author ID) is largely immutable.

    package com.blogplatform;
    
    public record Post(Long id, String title, String content, Long authorId) {}
    
  3. Update Main.java to use your new types.

    package com.blogplatform;
    
    public class Main {
        public static void main(String[] args) {
            // 1. Create a User object
            User author = new User(1L, "johndoe", "john.doe@example.com");
            System.out.println("Created user: " + author.getUsername());
    
            // 2. Create a Post record
            Post myPost = new Post(
                101L, 
                "Java for TypeScript Devs", 
                "This is a lesson about classes, interfaces, and records.", 
                author.getId()
            );
    
            // 3. Access data from the record
            System.out.println("Created post titled: " + myPost.title());
            System.out.println("Content: " + myPost.content());
    
            // 4. The auto-generated toString() is very helpful for debugging!
            System.out.println("Post details: " + myPost);
        }
    }
    

Run Main.java and observe the output.

Debugging Exercise

Now for the "runtime-first" part. Let's see how the Java compiler enforces an interface contract.

  1. Create an Auditable.java interface with a single method.
    package com.blogplatform;
    import java.time.LocalDateTime;
    
    public interface Auditable {
        LocalDateTime getCreatedAt();
    }
    
  2. Now, modify your Post record to implement it. But intentionally forget to add the method.
    // In Post.java
    public record Post(Long id, String title, String content, Long authorId) implements Auditable {
        // Oops, we didn't implement getCreatedAt()!
    }
    
  3. Your IDE (IntelliJ) will immediately show a red underline with an error: "Record 'Post' must implement abstract method 'getCreatedAt()' in 'Auditable'". This is nominal typing in action! The compiler is enforcing the contract.
  4. Fix the error by implementing the method. Since records are immutable, you can pass the creation time in the constructor.
    package com.blogplatform;
    import java.time.LocalDateTime;
    
    public record Post(
        Long id, 
        String title, 
        String content, 
        Long authorId, 
        LocalDateTime createdAt
    ) implements Auditable {
        @Override
        public LocalDateTime getCreatedAt() {
            return this.createdAt;
        }
    }
    
    You'll also need to update the instantiation in Main.java to pass the LocalDateTime.


Conclusion

You've just learned the fundamental building blocks for all object-oriented design in Java.

Key Takeaways:

  • class: The workhorse for creating objects with both state (fields) and behavior (methods). Use it when you need control over mutability and complex logic. It's analogous to a TypeScript class.
  • interface: Defines a contract of behaviors. It's the key to polymorphism and decoupled design. It differs from a TypeScript interface due to Java's nominal typing (implements) versus TypeScript's structural typing (shape-based).
  • record: A modern, concise syntax for creating simple, immutable data-carrier objects. Perfect for DTOs and value objects, saving you from writing tons of boilerplate.

In our next lesson, we'll see how to manage collections of these objects. Now that we can create User and Post objects, we'll need a way to store and manipulate them in lists, sets, and maps, drawing parallels to JavaScript's Array, Set, and Map.