← Java

Java · 07 / 18

Classes and constructors

Create a custom data type with controlled initial values.

  • Small
  • Basics
  • 15 min

Prerequisites: Arrays, lists, sets and maps

A class describes objects with related data and behaviour. A constructor creates an object. private restricts direct access to the class itself. Other parts of the program therefore cannot freely overwrite the data. Our class describes configuration for a small batch job.

Example files

01Keep data together

BatchConfig has title and count. final makes the fields non-reassignable after construction. The constructor checks count before an invalid object can exist.

Main.java · javaOpen file
public class Main {
  static final class BatchConfig {
    private final String title;
    private final int count;
    BatchConfig(String title, int count) {
      if (count <= 0) throw new IllegalArgumentException("count must be positive");
      this.title = title;
      this.count = count;
    }
    String describe() { return title + ": " + count; }
  }
  public static void main(String[] args) {
    var config = new BatchConfig("Letters", 3);
    System.out.println(config.describe());
  }
}

Run / check

java Main.java

02Create an object

new BatchConfig("Letters", 3) calls the constructor. this.title distinguishes the field from the parameter with the same name. Methods provide controlled access to information.

03Limit responsibility

The class knows nothing about HTTP, JavaFX or SQL. It only describes domain configuration. In the real PDF core, further objects validate mappings, limits and states.

Expected result

Letters: 3

Your exercise

Also check that title is neither null nor blank.

Show the solution and explanation

Add if (title == null || title.isBlank()) throw new IllegalArgumentException("title required"). || prevents isBlank from being called for null. The constructor creates an object only when all rules pass.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.