Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 201 ยท Object-Oriented Programming

Object-Oriented Programming

Learn what object-oriented programming means in Java - classes vs objects, state and behavior, encapsulation, inheritance, polymorphism, abstraction and how OOP compares to procedural code.

Up to now you've written programs as a list of steps: variables hold data, methods transform it, and main ties everything together. That style is called procedural programming, and it works well for small programs. As programs grow, though, the data and the methods that work on it drift apart. A change to how a bank balance is stored suddenly breaks ten methods in five files.

Object-oriented programming (OOP) organizes a program differently: data and the code that works on it live together in objects. An account object knows its own balance and knows how to deposit and withdraw. The rest of the program asks the account to do things instead of reaching into its data. Java was designed around this idea from day one; every Java program you've written already used objects (String, List, Scanner) even if you didn't create your own.

This lesson is the map for the whole chapter. You'll see what classes and objects are, compare procedural and object-oriented versions of the same program, and meet the four "pillars" of OOP at a glance. Each idea gets its own lesson afterwards, linked as we go.

Classes and objects

A class is a blueprint: it describes what data a kind of thing has and what it can do. An object is one concrete thing built from that blueprint. There is one String class, and millions of String objects; one Account class in a bank's code, and one Account object per customer account.

Every object has:

  • state: the data it holds, stored in fields (an account's owner and balance);
  • behavior: what it can do, defined by methods (deposit, withdraw, print a statement);
  • identity: it's a distinct thing, even if another object has the same state (two accounts can both hold 100 and still be different accounts).
Java One class, several objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

new Dog("Rex", 3) creates an object and runs the constructor, which fills in its fields. Each dog has its own name and age, so Rex's birthday doesn't change Luna. You'll learn the details in Classes and Objects, Fields and Instance Methods and Constructors.

Procedural vs object-oriented: the same program twice

Here is a tiny bank written procedurally. The data lives in arrays, and separate static methods work on those arrays by index:

Java A procedural bank

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

It works, but look at the problems that grow with size:

  • Anyone can change the data. Any line in the program can write balances[0] = 1_000_000. Rules like "a balance can't go below zero" have to be enforced everywhere, and one forgotten check is a bug.
  • Related data is scattered. An account's owner and balance live in two arrays that must stay in the same order. Add a third field and you need a third array.
  • Indexes stand in for things. withdraw(1, 90) means "withdraw from whoever is at position 1", which is easy to get wrong.

Now the object-oriented version. The data and the rules about it live in one class, and the outside world can only use the methods:

Java The same bank with objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program is a bit longer, but each rule now lives in exactly one place. If the bank later stores balances in cents, or logs every transaction, only Account changes; the code that uses accounts doesn't. That's the core promise of OOP: organize code around things, and let each thing guard its own data.

Procedural code isn't wrong. Short scripts, math helpers and data-crunching pipelines are often clearer as plain functions, and modern Java mixes both styles freely (static helpers, records, lambdas and streams). OOP pays off when a program has many kinds of things with rules and relationships: shops, games, banks, editors.

The four pillars at a glance

OOP is traditionally described with four ideas. You've just seen the first; here's a quick tour of all four, each with its own lesson later in the chapter.

1. Encapsulation: guard your data

Encapsulation means keeping an object's state private and exposing only methods that keep it valid. The private double balance above is encapsulated: the only way to change it is through deposit and withdraw, which check the rules. You can change how the data is stored without breaking callers. Details: Access Modifiers and Encapsulation, Getters and Setters.

2. Inheritance: build on an existing class

Inheritance lets a new class extend an existing one, reusing its fields and methods and adding or changing some. A SavingsAccount is an Account with interest. In Java you write class SavingsAccount extends Account. Inheritance is powerful but easy to overuse; often composition (an object has another object) is the better tool. Details: Inheritance.

3. Polymorphism: one call, many behaviors

Polymorphism ("many forms") means code can work with a general type and let each object respond in its own way. A loop that calls shape.area() doesn't need to know whether each shape is a circle or a rectangle:

Java Polymorphism and abstraction in a few lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

At runtime, each shape.area() call goes to the right class's method: that's dynamic dispatch. Adding a Triangle later means writing one new class; the loop doesn't change. Square extends Rectangle reuses the area formula and overrides only the name. Details: Polymorphism and Method Overriding.

4. Abstraction: depend on what, not how

Abstraction means describing what something does while hiding how. The Shape interface above says "every shape has an area and a name" and says nothing about formulas. The loop depends only on that promise. You use abstraction all the time: you call list.add(x) without knowing how ArrayList grows its internal array. Java expresses abstraction with interfaces and abstract classes.

The four pillars overlap: encapsulation hides data, abstraction hides implementation, and polymorphism is what lets abstraction work at runtime. Don't worry about memorizing definitions; you'll understand them by using them in the coming lessons.

Objects talking to objects

Real programs have many classes that cooperate. A shop has products, a cart holds products, an order is made from a cart. Each class does one job well and asks the others for help:

Java Small objects that cooperate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how responsibilities are divided: a CartLine knows how to compute its own subtotal, and the Cart adds up its lines. No single method knows everything. This "tell, don't ask" style, where you ask objects to do work rather than pulling out their data, is the heart of good object-oriented design. You'll refine it with principles like SOLID in Object-Oriented Design Principles.

How Java supports OOP

Java gives you a full toolbox, and this chapter walks through all of it:

Tool What it's for Lesson
class, new, fields, methods Define and create objects Classes and Objects
Constructors, this Set up objects correctly Constructors, The this Keyword
private, public, ... Encapsulation Access Modifiers
extends, super, @Override Inheritance and overriding Inheritance
interface, abstract Abstraction Interfaces
record Small immutable data carriers Records
enum A fixed set of named objects Enums
sealed, pattern matching Closed hierarchies, safe switch over types Sealed Classes

Everything in Java, except the eight primitive types, is an object, and every class ultimately extends java.lang.Object (The Object Class).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between a class and an object?

    The class describes fields and methods; each object created with new has its own copy of the fields and shares the class's methods.
  2. 2. Two Dog objects are created, a with age 3 and b with age 7. After a.haveBirthday() (which does age++), what are their ages?

    Each object has its own fields. A method called on a changes only a's state.
  3. 3. Making a field private and allowing changes only through methods that check the rules is called...

    Encapsulation hides an object's state and exposes only operations that keep it valid, so the rules live in one place.
  4. 4. A loop calls shape.area() on a List<Shape> holding circles and rectangles, and each object runs its own formula. Which idea is this?

    The same call runs different code depending on each object's actual class, decided at runtime. That's polymorphism.
  5. 5. What is the main advantage of the object-oriented bank over the procedural one in this lesson?

    The OOP version is slightly longer, but the private balance can only change through deposit and withdraw, so every rule is enforced in one place.

Summary

  • Procedural code keeps data and functions separate; object-oriented code bundles them into objects.
  • A class is a blueprint; an object is an instance with its own state (fields), shared behavior (methods) and its own identity.
  • Encapsulation keeps state private behind methods that enforce the rules.
  • Inheritance builds a new class on an existing one (extends); prefer composition when "is-a" doesn't really hold.
  • Polymorphism lets one call run different code depending on the object; abstraction (interfaces, abstract classes) lets code depend on what rather than how.
  • Good OOP divides responsibilities among small cooperating objects and tells them what to do instead of pulling out their data.

Next: Classes and Objects, where you'll define your own classes, create objects with new and see what references really are.