Thuta Learning
Java
IntermediateProgrammingBeginner

OOP Intro

JavaLesson 1520 min

What you'll walk away with

  • Explain what state, behaviour and identity mean for an object
  • Explain why objects are safer than parallel arrays
  • Create two objects with independent state from one class and call their methods
  • Describe encapsulation, inheritance, polymorphism and abstraction in one sentence each

Explain it simply

Explain it simply

Think of a student. They have facts about them, such as a name, an age and how many lessons they have finished, and they can do things, such as study or submit an assignment. Object-Oriented Programming (OOP) packs those two kinds of thing, data and behaviour, together into one object.

A class is the template used to build those objects. Write one Student class and you can create as many student objects as you like, Aung, Mya and so on, each keeping its own data. When Aung studies, Mya's lesson count does not change.

Problem → Why → Solution

The problem: parallel arrays drift apart

Before OOP, student data often lives in three arrays: names[i], ages[i] and gpas[i] are "agreed" to belong to the same student. Nothing enforces that agreement. Below, names is sorted but ages and gpas are not reordered, so Aung's row now shows Zaw's age and GPA, and no error appears anywhere.

Main.java
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    String[] names = {"Zaw", "Aung", "Mya"};
    int[] ages = {22, 20, 19};
    double[] gpas = {2.9, 3.2, 3.8};

    Arrays.sort(names); // ages and gpas are NOT reordered

    for (int i = 0; i < names.length; i++) {
      System.out.println(names[i] + " " + ages[i] + " " + gpas[i]);
    }
    // Aung 22 2.9  <- Zaw's data under Aung's name
  }
}

Why does this happen?

One student's data is spread across three places, tied together by nothing except a shared index. Put name, age and gpa inside one Student object and sorting moves all three together; there is simply no way for them to drift apart.

Core concept: object = state + behaviour + identity

An object has three things. State is the current values in its fields (name = "Aung", lessonsDone = 2). Behaviour is the methods that read and change that state (study()). Identity means each object exists separately in memory: two objects with identical field values are still two objects.

The main payoff of OOP is that the code changing the data sits right next to the data. If the rule "lessonsDone only ever goes up" is written inside study(), it is enforced in one place instead of being scattered through the program. A class is the declaration of an object type's fields and methods, and in Java it is also a new type: the variable Student aung has the type Student.

Java's OOP is usually described by four pillars; the table shows where each one is covered in depth. They are tools for controlling change, not a reason to write as many classes as possible: a class that owns a single responsibility is safe to modify.

PillarMeaning
EncapsulationFields stay private and change only through methods
InheritanceA subclass reuses a parent class's fields and methods
PolymorphismOne call behaves differently depending on the object
AbstractionShow the essential behaviour, hide the details

Consider composition ("has-a") before inheritance ("is-a"): a Course that has Lessons is far more natural than making Course a subclass of Lesson. Composition lets you swap or reuse the parts later without dragging a whole parent class along.

Every Java program lives inside a class; Main itself is one. Yet Main is not used as an object at all: its static main is just the starting point. Real OOP begins when you create objects with new and ask those objects to do the work.

Mental model: one template, many objects
  1. A class declares fields and methods
  2. new builds one object at a time
  3. Each object keeps its own state
  4. A method changes its object's state

aung.study() touches only aung's fields; mya is never affected.

General pattern

java
class TypeName {
  FieldType field;          // state: one copy per object

  void behaviour() {        // behaviour: uses this object's fields
    field = newValue;
  }
}

TypeName obj = new TypeName();  // create an object from the class
obj.field = value;              // set its state
obj.behaviour();                // ask it to do something

Fields without static get a separate copy in every object, and methods work on the fields of the object they are called on. Create an object with new, then use the dot (.) to reach its fields and methods.

Example: two Student objects

We build two objects from one Student class, ask aung to study twice and mya once, and watch lessonsDone count separately for each object. The single-file launcher (java Main.java) looks for main in the first class of the file, so Main comes first and Student follows without public. In a larger project each class would normally get its own .java file instead.

Main.java
public class Main {
  public static void main(String[] args) {
    Student aung = new Student();
    aung.name = "Aung";

    Student mya = new Student();
    mya.name = "Mya";

    aung.study();
    aung.study();
    mya.study();
  }
}

class Student {
  String name;
  int lessonsDone;

  void study() {
    lessonsDone++;
    System.out.println(name + " is studying Java. Lessons done: " + lessonsDone);
  }
}

Code breakdown

  1. Creating an objectStudent aung = new Student();

    new Student() builds a fresh object, and aung stores a reference to it. The second new creates a completely separate object.

  2. Setting stateaung.name = "Aung";

    The dot means "the name field of the object aung points to". mya.name belongs to a different object and is untouched.

  3. Per-object fieldsint lessonsDone;

    Without static, every object has its own lessonsDone. It is not initialised explicitly, so it starts at the int default of 0.

  4. Behaviour changes statelessonsDone++;

    Called on aung, study() increments aung's lessonsDone; called on mya, it increments mya's. That is why Aung reaches 2 while Mya shows 1.

You should see
Aung is studying Java. Lessons done: 1
Aung is studying Java. Lessons done: 2
Mya is studying Java. Lessons done: 1

When you do not need a full object: static helpers and records

OOP does not mean everything must become a full class. Logic that has no state and just turns input into output is fine as a static method, like Math.max(). For plain data that never changes, such as a subject paired with a score, Java 16 and later offer records: the single line record Grade(String subject, int score) {} makes the compiler generate the fields, a constructor, accessor methods (subject(), score()), equals() and toString().

Main.java
public class Main {
  static int percent(int part, int whole) { // stateless helper: static is enough
    return part * 100 / whole;
  }

  public static void main(String[] args) {
    Grade math = new Grade("Math", 87);
    System.out.println(math);
    System.out.println(math.subject() + " -> " + percent(math.score(), 100) + "%");
  }
}

record Grade(String subject, int score) {}

The output is Grade[subject=Math, score=87] and Math -> 87%. When there is behaviour that changes state, like study(), use a normal class as in this lesson: a record's fields are final and cannot change.

In real projects

Where this shows up in real projects

When designing an online shop, a school management system or a banking app, the first step is finding the nouns of the domain: User, Product, Order, Payment, Course, Lesson. Each becomes a class, and the verbs, such as order.addItem(), payment.refund() and course.publish(), become methods. Frameworks such as Spring Boot map each database row to an object and turn JSON request bodies into objects too.

Experienced teams try to give each class a single responsibility. An Order calculates totals and adds items, while sending email belongs to a separate class such as NotificationService, so switching email providers never requires touching Order. OOP is used to keep each change contained in one place, not to turn every procedure into a class.

Common mistakes

Common mistakes

1. Thinking getters and setters alone are encapsulation

Writing getX()/setX() for every field, with setLessonsDone(-5) happily accepted, is no better than a public field. Encapsulation means the object guards its own rules: let state change only through meaningful methods such as study().

2. The "god class" that does everything

A single SchoolManager class that stores students, calculates grades, prints PDFs and sends email means every change touches that one class. Split the responsibilities into Student, GradeCalculator and ReportPrinter.

3. Reaching for inheritance just to reuse code

Writing Course extends ArrayList<Lesson> drags in unwanted methods such as clear() and remove(). Composition, a Course holding a List<Lesson> field, is simpler and safer.

Best practices

Best practices

  • Name classes with nouns (Student, Invoice) and methods with verbs (study, pay).
  • If you cannot describe a class's job in one sentence, consider splitting it.
  • Check a rule, such as a 16-30 degree range, inside the class that owns the data, not in every caller.

Mini challenge

Mini challenge: two thermostat objects

Write a Thermostat class that holds one room's target temperature and test it with two objects. The rule (stay between 16 and 30) must be enforced inside the methods.

  • Fields: String room and int target
  • raise() and lower() change the target by 1 degree, never below 16 or above 30
  • report() prints a line like "Bedroom is set to 22 C"
  • In main, lower bedroom (24) twice, raise office (29) twice, then report both
Main.java
public class Main {
  public static void main(String[] args) {
    // TODO: create bedroom (target 24) and office (target 29)
    // TODO: lower bedroom twice, raise office twice
    // TODO: call report() on both
  }
}

class Thermostat {
  static final int MIN = 16;
  static final int MAX = 30;

  // TODO: fields room and target

  void raise() {
    // TODO: add 1, but never go above MAX
  }

  void lower() {
    // TODO: subtract 1, but never go below MIN
  }

  void report() {
    // TODO: print "<room> is set to <target> C"
  }
}

Expected: Bedroom is set to 22 C Office is set to 30 C

Show hint

Inside raise(), check before incrementing: if (target < MAX) target++;. Office starts at 29, so the second raise() must stop at 30.

Show solution
Main.java
public class Main {
  public static void main(String[] args) {
    Thermostat bedroom = new Thermostat();
    bedroom.room = "Bedroom";
    bedroom.target = 24;

    Thermostat office = new Thermostat();
    office.room = "Office";
    office.target = 29;

    bedroom.lower();
    bedroom.lower();
    office.raise();
    office.raise();

    bedroom.report();
    office.report();
  }
}

class Thermostat {
  static final int MIN = 16;
  static final int MAX = 30;

  String room;
  int target;

  void raise() {
    if (target < MAX) {
      target++;
    }
  }

  void lower() {
    if (target > MIN) {
      target--;
    }
  }

  void report() {
    System.out.println(room + " is set to " + target + " C");
  }
}

Quick quiz 1 / 3

In the example, after aung.study() runs twice and mya.study() once, what is mya.lessonsDone?

Quick quiz 2 / 3

What is the main benefit of Student objects over parallel arrays such as names[] and ages[]?

Quick quiz 3 / 3

Which is the most suitable way to model the relationship between Course and Lesson?

What to remember

  • An object has state (fields), behaviour (methods) and identity; a class is both its template and its type.
  • Keeping data next to the code that changes it lets rules be enforced in one place.
  • Fields without static get a separate copy in every object.
  • The four pillars are tools for controlling change; consider composition before inheritance.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

OOP Intro | Thuta Learning