← Java from Scratch Lesson 28 of 88 · 5 XP

OOP

Theory

Machine translation, not yet reviewed by a native speaker.

Object-oriented programming builds a program out of objects: each has data (fields) and behaviour (methods).

  • a class is a blueprint: "an enemy has health and can attack";
  • an object (an instance) is a specific thing made from the blueprint: an orc with 50 HP.

Four ideas:

  1. Encapsulation — the data is hidden (private) and can be changed only through methods with checks.
  2. Inheritance — class Boss extends Enemy: take everything from the parent and add your own.
  3. Polymorphism — enemy.attack() works differently for different enemies.
  4. Abstraction — show "what it can do" (the interface), hide "how it's done".

In Java OOP isn't optional: all code lives in a class, even main. All classes are descendants of Object (that's why every object has the methods toString(), equals(), hashCode()).

What's under the hood. new allocates an object on the heap, and the variable holds only a reference. When nothing refers to an object any more, the garbage collector (GC) removes it — you don't need free as in C. Primitives (int, double…) live right in the variable, so copying them copies the value, while copying an object copies the reference.

Next — each idea in practice.

Sign up for free to mark finished lessons and track your progress.