Free degree-level programming lessons for careful independent study.

Degree Level Programmes · Programming 2 · Lesson 4

Objects, Encapsulation and Abstraction

Model program concepts as objects with private state, public behaviour and clear abstractions.

Lesson Overview

Model program concepts as objects with private state, public behaviour and clear abstractions.

Portfolio focus: Model a library loan with three classes.

ConceptObject-oriented design
Run fileObjectsEncapsulationAndAbstractionDemo.java
BaselineAda
Evidence3 tasks

Starter: think before typing

Before running this object-oriented design example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Ada`; predict how the focus line helps produce that evidence.

Learning Objectives

  • Create classes with fields, constructors and methods.
  • Use encapsulation to protect object state.
  • Explain abstraction as purposeful simplification.
  • Design a small object model from a brief.

Learning Outcomes

  • By the end of the lesson, you can create classes with fields, constructors and methods.
  • By the end of the lesson, you can use encapsulation to protect object state.
  • By the end of the lesson, you can explain abstraction as purposeful simplification.
  • By the end of the lesson, you can design a small object model from a brief.

Why this idea exists

Object-oriented programming grew from attempts to model software as interacting entities with state and behaviour. Languages such as Simula and Smalltalk shaped ideas that later influenced Java.

Encapsulation protects an object from being put into an invalid state by random outside code. Abstraction lets programmers work with a useful public idea while hiding representation details that may change.

The point is not to create classes for everything. The point is to find concepts in the problem domain that deserve stable names, rules and responsibilities.

Deep dive

Mechanism in this example

The important mechanism is visible around `Student student = new Student("Ada");`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.

Design pressure

The point is not to create classes for everything. The point is to find concepts in the problem domain that deserve stable names, rules and responsibilities.

Failure mode to watch

For Objects, Encapsulation and Abstraction, deliberately disturb the assumption behind `Student student = new Student("Ada");`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the object-oriented design design.

Extension step

Extend the example by doing this: Add private fields and constructor checks. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.

Portfolio standard

The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: explain what details the public methods hide.

Lesson visual

Photo of real index cards labelled Student, Module and Mark with UML-style links beside Java class code.
Photo of real index cards labelled Student, Module and Mark with UML-style links beside Java class code.Download visual

Type this and run it

Create ObjectsEncapsulationAndAbstractionDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.

public class ObjectsEncapsulationAndAbstractionDemo {
  public static void main(String[] args) {
    Student student = new Student("Ada");
    System.out.println(student.displayName());
  }
}

class Student {
  private final String name;

  Student(String name) {
    if (name.isBlank()) throw new IllegalArgumentException("Name required");
    this.name = name;
  }

  String displayName() {
    return name;
  }
}

Build and run it with:

javac ObjectsEncapsulationAndAbstractionDemo.java && java ObjectsEncapsulationAndAbstractionDemo

Expected baseline: Ada

Run the code in your browser

Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates object-oriented design and compare the new behaviour with the reference output.

Line-by-line explanation

Read the code as a sequence of responsibilities. The focus line for this lesson is Student student = new Student("Ada");; the surrounding lines prepare it, use its result or make the behaviour observable.

public class ObjectsEncapsulationAndAbstractionDemo {

This names the runnable class for the Objects, Encapsulation and Abstraction example, giving the compiler and JVM one clear unit to build.

public static void main(String[] args) {

This is the program entry point. In Objects, Encapsulation and Abstraction, it keeps the demonstration of object-oriented design in one traceable starting script.

Student student = new Student("Ada");

This introduces student as named state for Objects, Encapsulation and Abstraction. Later lines can read, update, pass or print that specific value as evidence.

System.out.println(student.displayName());

This prints student.displayName() as the observable evidence for Objects, Encapsulation and Abstraction. The output lets the learner check whether the object-oriented design idea behaved as predicted.

}

This closes the innermost Objects, Encapsulation and Abstraction block, so the immediately preceding method, branch or loop has finished.

}

This closes the outer Objects, Encapsulation and Abstraction structure, returning the reader to the surrounding class or file.

class Student {

This starts a supporting class so Objects, Encapsulation and Abstraction can separate the lesson idea into its own named responsibility.

private final String name;

This declares name as object state for the Objects, Encapsulation and Abstraction design without exposing it directly. Later constructors or methods should give it a controlled value.

Student(String name) {

This constructor prepares a new object so the Objects, Encapsulation and Abstraction example can use it in a valid state.

if (name.isBlank()) throw new IllegalArgumentException("Name required");

This makes the Objects, Encapsulation and Abstraction decision point. Trace the condition first, then trace only the branch that can actually run.

this.name = name;

This assignment changes name in Objects, Encapsulation and Abstraction to name. Trace where that new value is used next.

}

This closing brace number 3 completes another layer of the Objects, Encapsulation and Abstraction source structure Java has been checking.

String displayName() {

This starts displayName, a named Objects, Encapsulation and Abstraction operation. Its parameters describe what information comes in; its body decides what work is done.

return name;

This sends a Objects, Encapsulation and Abstraction result back to the caller, so the surrounding code can use the answer.

}

This closing brace number 4 completes another layer of the Objects, Encapsulation and Abstraction source structure Java has been checking.

}

This closing brace number 5 completes another layer of the Objects, Encapsulation and Abstraction source structure Java has been checking.

Worked example

From code to explanation

Problem: Use Objects, Encapsulation and Abstraction to complete a small portfolio-quality step: Model a library loan with three classes.

Method: Locate the line `Student student = new Student("Ada");`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.

Reveal worked answer

The checked run should produce `Ada`. A strong answer links the result back to object-oriented design: what was created, selected, stored, called or protected, and why that matters for the portfolio task.

Trace the program

Before: Before the key operation, identify the relevant value, object, branch or resource that the object-oriented design concept depends on.

During: Trace `Student student = new Student("Ada");` as the Objects, Encapsulation and Abstraction example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.

After: Compare the run with the expected evidence: `Ada`.

Change: Now add private fields and constructor checks, run again, and explain the smallest reason the behaviour changed.

Common misconception

A common mistake in objects, encapsulation and abstraction is treating the example as a finished answer. For object-oriented design, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?

Quick checks

1. In this Objects, Encapsulation and Abstraction example, what is the best reason to focus on `Student student = new Student("Ada");`?

2. Which evidence is strongest after you edit and rerun this example?

How to study this lesson

For Objects, Encapsulation and Abstraction, predict how object-oriented design changes the run before you press Run.

Use the first portfolio task as your main edit: Model a library loan with three classes.

Use the second task as your variation: Add private fields and constructor checks.

Finish with evidence, not a diary entry: Explain what details the public methods hide.

Portfolio Practice

  1. Model a library loan with three classes.
  2. Add private fields and constructor checks.
  3. Explain what details the public methods hide.

Final self-check

Can you explain the key operation?

Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Ada appears.

Can you justify the portfolio evidence?

Your evidence should include the original run, one edited run, and a short note explaining how the edit affected object-oriented design.

Study route

Practise object-oriented design by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.

Next, move into Inheritance for Reuse and carry forward one improvement from this lesson into the next program.