Skip to content
Qyubie Learn
Java tutorialLesson 9 of 18 · tap to see all lessons

Java tutorial · Beginner

Introduction to Object-Oriented Programming in Java

Procedural vs object-oriented programming, why OOP helps, how objects combine attributes and behaviors, and a first look at the four pillars of OOP.

  • Qyubie Learn Editorial Team
  • Published
  • 7 min read

Includes 3 quick checks you can do right here.

Until now, our programs have been a list of steps inside main, with data kept in loose variables and arrays. That works for small tasks, but a real system such as an enrollment or library system has hundreds of pieces of data and actions. Object-oriented programming (OOP) organizes a program around objects: things that keep their own data together with the actions that use it.

By the end of this lesson you will be able to:

  • explain the difference between procedural and object-oriented programming,
  • describe an object by its attributes and behaviors,
  • list the advantages and common uses of OOP, and
  • name and briefly explain the four pillars of OOP.

Procedural programming: steps and loose data

In procedural programming (the style of C, and of the earlier lessons), you write procedures, meaning functions or methods, that act on data stored separately.

Here is a procedural way to keep two students' records:

String[] names = {"Ana", "Ben"};
double[] grades = {88.5, 74.0};

for (int i = 0; i < names.length; i++) {
    String status = grades[i] >= 75 ? "passed" : "failed";
    System.out.println(names[i] + " " + status);
}

Output:

Ana passed
Ben failed

It works, but nothing ties names[0] to grades[0] except their position. If one array is sorted and the other isn't, the data no longer lines up. Add a course, a year level, and an email, and you're juggling five parallel arrays, while any code anywhere can change any of them.

(condition ? a : b is the ternary operator: it gives a if the condition is true, otherwise b.)

Object-oriented programming: data and behavior together

In OOP, you first describe what a student is with a class. Then you create one object per student. Each object carries its own data and knows how to work with it:

class Student {
    String name;
    double grade;

    boolean hasPassed() {
        return grade >= 75;
    }
}

public class School {
    public static void main(String[] args) {
        Student a = new Student();
        a.name = "Ana";
        a.grade = 88.5;

        Student b = new Student();
        b.name = "Ben";
        b.grade = 74.0;

        System.out.println(a.name + " passed? " + a.hasPassed());
        System.out.println(b.name + " passed? " + b.hasPassed());
    }
}

Output:

Ana passed? true
Ben passed? false

Now a name and its grade can never get separated: they live in the same object. The rule for passing is written once, inside Student, instead of being repeated wherever it's needed. You'll learn every part of this code in the next lessons.

ProceduralObject-oriented
Built fromprocedures (functions)objects created from classes
Dataseparate from the code that uses itbundled with its methods in an object
Focusthe steps to performthe things in the problem and what they do
Changing dataany code can change any variablean object controls access to its own data
Example languagesC, PascalJava, C#, Python, C++

Objects: attributes and behaviors

Look around a classroom and you see objects: students, chairs, a projector. Each has:

  • Attributes (also called state, fields, or properties): what it has or is. A student has a name, an ID, and a course.
  • Behaviors (methods): what it does, or what can be done to it. A student can enroll, take a quiz, or compute a GWA.
ObjectAttributesBehaviors
Studentname, ID, course, gradesenroll(), computeGwa()
Bank accountaccount number, owner, balancedeposit(), withdraw()
Booktitle, author, ISBN, availableborrow(), returnBook()
Phonebrand, battery levelcall(), charge()

A class is the blueprint, such as the plan for a student record. An object is one actual thing built from that blueprint, such as Ana's record or Ben's record. One class can create any number of objects.

Quick check

In a library system, which of these is a behavior of a Book object rather than an attribute?

Why use OOP?

  • Modularity: each class is a self-contained piece, so you can build and test the Student class separately from the Course class.
  • Reusability: write a class once and create as many objects as you need, or reuse the class in another project.
  • Easier maintenance: to change how passing is decided, you edit one method in one class.
  • Data protection: an object can hide its data and allow changes only through its methods (encapsulation, lesson 12).
  • It models the real world: the classes match the things people talk about, like students, subjects, and payments, which makes large systems easier to design and discuss.

OOP is used in nearly every large application: school and hospital information systems, banking, games (every character is an object), Android apps, and desktop programs.

The four pillars of OOP

These four ideas run through the rest of this course. Here's a first look; each gets its own lesson later.

1. Encapsulation. Keep an object's data private and let other code change it only through methods that check the rules. A bank account doesn't let anyone set the balance directly; you must call deposit() or withdraw().

2. Inheritance. A new class can extend an existing one and reuse its attributes and methods. A Teacher and a Student are both a kind of Person, so the shared parts (name, birthday) are written once in Person.

3. Polymorphism. "Many forms": the same method call can behave differently depending on the object. Calling computePay() on a full-time employee and on a part-time employee runs different formulas.

4. Abstraction. Show only what's needed and hide the details. You call account.withdraw(500) without knowing how the bank's system records it, just as you drive a car without knowing how the engine works.

Quick check

A class keeps its balance field private and only changes it through deposit() and withdraw(), which reject negative amounts. Which pillar is this?

Quick check

Car, Motorcycle, and Truck all reuse the speed and plateNumber attributes from a Vehicle class. Which pillar is this?

Common mistakes

  • Mixing up class and object. Student is the class (the blueprint); a and b are objects (instances).
  • Thinking OOP replaces everything you've learned. Methods still use variables, ifs, loops, and arrays. OOP organizes them.
  • Making one giant class that does everything. Each class should represent one thing and do its own job.

Summary

  • Procedural programming organizes code around steps; OOP organizes it around objects.
  • An object has attributes (data) and behaviors (methods). A class is the blueprint, and an object is one instance of it.
  • OOP gives modularity, reuse, easier maintenance, and data protection.
  • The four pillars are encapsulation, inheritance, polymorphism, and abstraction.

Next lesson: classes and objects: writing your own class and creating objects from it.

References and further reading