Basic OOP Concepts, Explained with simplified examples in Java

Learn the fundamental concepts of Object-Oriented Programming (OOP) in Java with simple explanations and examples.

15 min read
OOPJavaconcepts

Introduction

Have you ever tried organizing your closet or a backpack? You group similar things together, right? That's what Object-Oriented Programming (OOP) does for code. Its a way of organizing code that's clean, scalable, and mirrors how we think about the real world.

What is Object Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a way of writing code where everything revolves around objects, a reusable piece of code that represent real world things. These objects are created from classes, which act like blueprints.

OOP help you build program that are:

  • Modular (broken into smaller, manageable pieces)
  • Reusable (reuse existing code without rewriting)
  • Maintainable (easier to update and improve)

OOP is built on important concepts like encapsulation, abstraction, inheritance, and polymorphism. These ideas help make your code more organized and efficient. In the next sections, we'll explore each of these concepts in detail to help you understand how OOP works in Java.

The four pillars of OOP

Redis Logo

OOP is built on four main principles, often referred to as the "four pillars of OOP." These principles help you design and structure your code effectively. Let’s break down each pillar with simple explanations and examples to see how they work in Java.

1. Encapsulation

Encapsulation means bundling the data (variables) and code (methods) that work on that data into one unit (a class), and restricting direct access to the internal state.

The key idea of encapsulation is to only allow access to data through public methods, while keeping the data itself private.

In Java, you can achieve encapsulation by using access modifiers like private, protected, and public. Here's a simple example:

class Person {
    private String name; // Private attribute
 
    // Public method to set the name
    public void setName(String name) {
        this.name = name;
    }
 
    // Public method to get the name
    public String getName() {
        return name;
    }
}

To use this class, you would create an instance of Person, set the name using setName, and retrieve it using getName method.

2. Abstraction

Abstraction means hiding the complex implementation details and showing only the essential features of an object.

The key idea of abstraction is to lets you focus on what an object does, not how it does it. This makes code cleaner and easier to use.

In java, you can achieve abstraction using abstract classes and interfaces. Here's a simple example:

abstract class Animal {
    abstract void makeSound(); // Abstract method
}
 
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof!");
    }
}

In this example, Animal is an abstract class with an abstract method makeSound. The Dog class extends Animal and provides its own implementation of makeSound. You can create a Dog object and call its makeSound method without worrying about the details of how the sound is made.

We can also use interfaces to achieve abstraction. An interface defines a contract that classes must follow, without providing any implementation details. Here's an example

interface Drawable {
    void draw(); // Method without implementation
}
 
class Circle implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

In this example, the Drawable interface defines a method draw, and the Circle class implements that interface, providing its own implementation of the draw method. This allows you to create different shapes that can be drawn without worrying about their specific implementations.

3. Inheritance

Inheritance allows a new class (subclass/child) to inherit properties and behaviors from an existing class (superclass/parent), promoting code reuse.

The key idea of inheritance is to create a new class that builds upon an existing class, inheriting its attributes and methods. This allows us to use the functionality of the parent class without rewriting code.

In Java, you can achieve inheritance using the extends keyword. Here's a simple example:

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}
 
class Dog extends Animal {
    void bark() {
        System.out.println("Woof!");
    }
}

In this example, the Dog class extends the Animal class, inheriting its eat method. The Dog class can also have its own methods, like bark. You can create a Dog object and call both eat and bark methods.

4. Polymorphism

Polymorphism means the ability of an object to take on many forms. It allows the same method name to behave differently based on the object that is invoking it.

The key idea of polymorphism is to allow methods to be used in different ways, depending on the context. This can be achieved through method overloading and method overriding.

In Java, you can achieve polymorphism through method overloading and method overriding. Here's a simple example:

class MathUtils {
    // Method overloading: same method name, different parameters
    int add(int a, int b) {
        return a + b;
    }
    double add(double a, double b) {
        return a + b;
    }
}

In this example, the add method is overloaded with two different parameter types (int and double). You can call add with either type, and Java will determine which version to use based on the arguments you provide.

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}
class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}
class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Cat meows");
    }
}

In this example, the Animal class has a method sound, which is overridden in the Dog and Cat classes. When you call the sound method on an Animal reference that points to a Dog or Cat object, Java will invoke the appropriate method based on the actual object type.

Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
Animal myCat = new Cat();
myCat.sound(); // Output: Cat meows

This demonstrates polymorphism, where the same method name (sound) behaves differently based on the actual object type (Dog or Cat).

TL;DR: Quick Summary of the Four Pillars of OOP

PillarDescriptionReal-life AnalogyJava Keywords/Usage
EncapsulationHides internal data and logicBank account info is privateprivate, get/set
AbstractionHides how things work, shows what they doCar pedal hides complex mechanicsabstract, interface
InheritanceOne class gets behavior from anotherDog inherits behavior from Animalextends
PolymorphismOne method, many behaviorsSame remote button = different actionoverride, dynamic binding

Conclusion

Object-Oriented Programming (OOP) is a powerful way to organize and structure your code. By understanding the concepts like encapsulation, abstraction, inheritance, and polymorphism, you can create clean, modular, and reusable code that mirrors real-world concepts.

Reynaldi Neo Ramadhani

Reynaldi Neo Ramadhani

Software developer focused on creating clean, user-friendly experiences. I write about web development, programming, and technology.

Related Articles