Learn Java · 4/15

Object-Oriented Programming (OOP) Part 2: Core Pillars

11 min read

Welcome back! Now that you have a basic understanding of objects and classes, let's dive deeper into the four fundamental pillars of Object-Oriented Programming. These concepts are the secret sauce that makes OOP so powerful and widely used in the software industry. We'll explore Encapsulation, Inheritance, Polymorphism, and Abstraction.


1. Encapsulation: Protecting Your Data State 🛡️

The Problem: Imagine you're building a BankAccount class. This class has a balance variable. If any part of your code could just reach in and change that balance directly (e.g., myAccount.balance = -1000000;), it would be chaos! You could have negative balances, or unauthorized changes, leading to a complete mess. You need a way to protect your object's data from accidental or malicious modification.

The Solution: Encapsulation

Encapsulation is the practice of bundling an object's data (its fields or variables) and the methods that operate on that data into a single unit—the class. More importantly, it involves hiding the internal state of an object from the outside world. You do this by making your fields private and providing public methods to access and modify them.

This creates a protective barrier around your data, ensuring it can only be changed in a controlled manner.

How It Works in Java:

  1. Private Fields: You declare the class's member variables as private. This means they can only be accessed from within the same class.
  2. Public Getters and Setters: You provide public methods to get (read) and set (write) the values of these private fields. Setters can include logic to validate the new value before changing the field.

Example: A Safe Bank Account

Let's see it in action.

java
public class BankAccount {
    // 1. Private field: Cannot be accessed directly from outside this class.
    private double balance;

    // Constructor to initialize the account
    public BankAccount(double initialBalance) {
        if (initialBalance > 0) {
            this.balance = initialBalance;
        } else {
            this.balance = 0;
        }
    }

    // 2. Public Getter: Allows controlled read-only access to the balance.
    public double getBalance() {
        return this.balance;
    }

    // 3. Public Setter (for depositing money)
    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Deposit amount must be positive.");
        }
    }

    // 4. Another public method that modifies the state
    public void withdraw(double amount) {
        if (amount > 0 && amount <= this.balance) {
            this.balance -= amount;
            System.out.println("Withdrew: " + amount);
        } else {
            System.out.println("Withdrawal amount is invalid or exceeds balance.");
        }
    }
}

Why This Is an Industry Standard:

  • Data Integrity: As you can see in the deposit and withdraw methods, we can add validation logic. This prevents nonsensical data (like a negative deposit) from corrupting the object's state.
  • Maintainability: If you need to change how the balance is stored (e.g., change its data type), you only have to update the BankAccount class. All other parts of your application that use this class via its public methods won't need to change.
  • Flexibility: You have full control. You could make a field read-only by providing a getter but no setter.

Fun Fact: The concept of encapsulation is like a vending machine. You can't just reach inside and grab a soda. You have to use the public interface (the buttons and the coin slot) to interact with it. The machine's internal state (inventory, cash) is encapsulated and protected from direct access.


2. Inheritance: Reusing Code with Superclasses and Subclasses 🧬

The Problem: You're creating a set of classes to represent animals, like Dog and Cat. You quickly realize they share common attributes (name, age) and behaviors (eat(), sleep()). Writing this same code in every single animal class is tedious, error-prone, and a nightmare to update.

The Solution: Inheritance

Inheritance is a powerful mechanism where a new class can be derived from an existing class. The new class, called a subclass (or child class), inherits the fields and methods of the existing class, called the superclass (or parent class). This promotes code reuse and establishes a logical hierarchy between classes.

How It Works in Java:

You use the extends keyword to create a subclass.

Example: The Animal Kingdom

Let's create a general Animal superclass and then more specific Dog and Cat subclasses.

java
// Superclass
public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }
}

// Subclass
// Dog inherits `name`, `getName()`, and `eat()` from Animal
public class Dog extends Animal {

    // Dog's own constructor
    public Dog(String name) {
        // 'super(name)' calls the constructor of the superclass (Animal)
        super(name);
    }

    // Dog's own method
    public void bark() {
        System.out.println(getName() + " says: Woof!");
    }
}

// Another Subclass
public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }

    public void meow() {
        System.out.println(getName() + " says: Meow!");
    }
}

// --- Main class to run the code ---
public class Zoo {
    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy");
        Cat myCat = new Cat("Whiskers");

        myDog.eat();  // Inherited from Animal
        myDog.bark(); // Defined in Dog

        myCat.eat();  // Inherited from Animal
        myCat.meow(); // Defined in Cat
    }
}

Why This Is an Industry Standard:

  • DRY Principle (Don't Repeat Yourself): You write common code once in the superclass and reuse it across multiple subclasses.
  • Logical Structure: It creates a natural and easy-to-understand "is-a" relationship (e.g., a Dog is an Animal). This makes complex software systems easier to model and reason about.
  • Extensibility: You can easily add new animals (e.g., class Bird extends Animal) without touching the existing Dog or Cat classes.

A Little Exaggeration: Imagine if every time a car manufacturer designed a new model, they had to reinvent the wheel, the engine, and the steering wheel from scratch. Inheritance is like starting with a proven car chassis (the superclass) and then adding the unique features for your new model (the subclass).


3. Polymorphism: One Interface, Multiple Implementations 🎭

The Problem: Let's continue with our Animal example. What if you wanted to have a list of different animals and make them all produce their unique sound? Without polymorphism, you might end up writing a messy if-else chain:

java
// The messy way
if (animal is a Dog) {
    animal.bark();
} else if (animal is a Cat) {
    animal.meow();
} // ... and so on for every animal

This is not flexible. Every time you add a new animal, you have to modify this code.

The Solution: Polymorphism

Polymorphism, which means "many forms," is the ability for different objects to respond to the same message (method call) in different ways. It allows you to treat an object of a subclass as an object of its superclass. However, when you call an overridden method, the Java Virtual Machine (JVM) is smart enough to execute the subclass's version of that method.

How It Works in Java:

This is primarily achieved through method overriding.

  1. Define a method in the superclass.
  2. Provide a specific implementation of that same method in the subclass (using the @Override annotation is a best practice).

Example: A Symphony of Animal Sounds

Let's add a makeSound() method to our animal hierarchy.

java
// Superclass
public class Animal {
    // ... (name and constructor from before)
    
    public void makeSound() {
        System.out.println("Some generic animal sound");
    }
}

// Subclass
public class Dog extends Animal {
    // ... (constructor from before)

    @Override // Good practice to use this annotation
    public void makeSound() {
        System.out.println("Woof!");
    }
}

// Another Subclass
public class Cat extends Animal {
    // ... (constructor from before)

    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

// --- Main class to demonstrate polymorphism ---
public class Zoo {
    public static void main(String[] args) {
        // Notice the array is of type Animal, but it holds Dog and Cat objects.
        Animal[] animals = {new Dog("Buddy"), new Cat("Whiskers"), new Animal("Generic")};

        for (Animal animal : animals) {
            // The SAME method call, but DIFFERENT behavior at runtime!
            animal.makeSound();
        }
    }
}

Output:

ada
Woof!
Meow!
Some generic animal sound

Why This Is an Industry Standard:

  • Flexibility and Decoupling: The code that uses the Animal objects (the for loop) doesn't need to know the specific type of animal it's dealing with. It just needs to know that it can call the makeSound() method. You can add a Bird class, and the loop will work without any changes. This is a core principle of good design.
  • Reusable Code: You can write generic methods that operate on a superclass type, and they will work seamlessly with any future subclasses.

Real-World Scenario: Think of a USB port. You can plug in a mouse, a keyboard, or a flash drive. The port (the interface) is the same, but each device (the implementation) responds differently when connected. That's polymorphism in action!


4. Abstraction: Abstract Classes vs. Interfaces 👻

The Problem: Sometimes you want to create a superclass that defines a general concept but can't or shouldn't be instantiated on its own. For example, what is an "Animal" object? It's too generic. You can have a Dog or a Cat, but not just an "Animal." You want to force all subclasses to implement certain methods (like makeSound()), but you can't provide a meaningful implementation in the superclass itself.

The Solution: Abstraction

Abstraction is about hiding the implementation details and showing only the essential features to the user. In Java, we achieve this using abstract classes and interfaces.

Abstract Classes

An abstract class is a class that cannot be instantiated. It serves as a blueprint for other classes. It can have a mix of regular methods with implementations and abstract methods, which are methods without a body that must be implemented by any concrete (non-abstract) subclass.

Use an abstract class when:

  • You want to share code among several closely related classes.
  • You expect classes that extend your abstract class to have many common methods or fields.
  • You are defining a base for an "is-a" relationship.

Example: Abstract Animal

java
public abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    
    // An abstract method - no implementation, just a signature.
    // It acts as a contract: any subclass MUST provide an implementation.
    public abstract void makeSound();

    // A regular, concrete method
    public void sleep() {
        System.out.println(getName() + " is sleeping... zzz");
    }
}

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    // Must implement the abstract method from Animal
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

Interfaces

An interface is a completely abstract "class" that is used to group related methods with empty bodies. Think of it as a pure contract of behaviors. A class can implement an interface, thereby promising to provide an implementation for all of its abstract methods.

A key feature is that a class can extend only one superclass, but it can implement multiple interfaces. This is how Java achieves a form of multiple inheritance.

Use an interface when:

  • You expect that unrelated classes would implement your interface (e.g., a Bird and an Airplane can both implement Flyable).
  • You want to specify the behavior of a particular data type but are not concerned about who implements its behavior.
  • You want to define a "can-do" or "has-a" capability.

Example: A Flyable Interface

java
public interface Flyable {
    // Interface methods are public and abstract by default.
    void fly();
}

public class Bird implements Flyable {
    @Override
    public void fly() {
        System.out.println("Flying with flapping wings.");
    }
}

public class Airplane implements Flyable {
    @Override
    public void fly() {
        System.out.println("Flying with jet engines.");
    }
}

Key Differences Summarized

Feature Abstract Class Interface
Instantiation Cannot be instantiated. Cannot be instantiated.
Methods Can have both abstract and concrete (with body) methods. Traditionally only abstract methods. Java 8+ allows default and static methods with bodies.
Fields Can have instance variables (state). Can only have public static final constants.
Inheritance A class can extend only one abstract class. A class can implement multiple interfaces.
Purpose To provide a common base for related classes (is-a). To define a contract of capabilities (can-do).

Industry Rule of Thumb: "Favor interfaces over abstract classes." Start with an interface to define the necessary behaviors. If you find that multiple implementation classes are writing the exact same code for some of those behaviors, then you might consider using an abstract class to provide a shared base implementation.


Further Reading 📚

For a more in-depth look, check out the official Oracle Java documentation:

Challenge

OOP Pillars Challenge

Your task is to design a basic employee payroll system by correctly applying the four pillars of Object-Oriented Programming: Encapsulation, Inheritance, Abstraction, and Polymorphism.

Requirements:

  1. Abstraction (Interface):

    • Create an interface named Payable with a single abstract method signature: double calculatePay(). This interface defines the contract for any object that can be paid.
  2. Abstraction (Abstract Class) & Encapsulation:

    • Create an abstract class named Employee that implements the Payable interface.
    • It must contain two private instance variables: employeeId (String) and name (String).
    • Implement encapsulation by providing public getter methods for these variables (getEmployeeId(), getName()). There should be no setter methods to make them read-only after creation.
    • Create a public constructor that accepts and initializes employeeId and name.
  3. Inheritance & Polymorphism:

    • Create a concrete class SalariedEmployee that extends Employee.
      • It should have a private instance variable: annualSalary (double).
      • Its constructor should accept employeeId, name, and annualSalary, using the super keyword to initialize the inherited fields.
      • Implement the calculatePay() method to return the weekly salary (annual salary / 52).
    • Create another concrete class HourlyEmployee that extends Employee.
      • It should have two private instance variables: hourlyRate (double) and hoursWorked (double).
      • Its constructor should accept employeeId, name, hourlyRate, and hoursWorked.
      • Implement the calculatePay() method to return the total pay (hourlyRate * hoursWorked). If hours worked exceed 40, any hours over 40 should be paid at 1.5 times the hourly rate.

Expected result

Your solution should consist of one interface and three classes structured as follows.

1. Payable Interface

A public interface defining the contract for payment.

java
public interface Payable {
    double calculatePay();
}

2. Employee Abstract Class

An abstract base class for all employee types, implementing Payable and encapsulating common data.

java
public abstract class Employee implements Payable {
    private String employeeId;
    private String name;

    public Employee(String employeeId, String name) {
        this.employeeId = employeeId;
        this.name = name;
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public String getName() {
        return name;
    }

    // Note: The abstract class does not need to implement calculatePay()
    // because it is abstract. Subclasses are forced to implement it.
}

3. SalariedEmployee Class

A concrete class for employees paid with a fixed annual salary.

java
public class SalariedEmployee extends Employee {
    private double annualSalary;

    public SalariedEmployee(String employeeId, String name, double annualSalary) {
        super(employeeId, name);
        this.annualSalary = annualSalary;
    }

    @Override
    public double calculatePay() {
        return this.annualSalary / 52.0;
    }
}

4. HourlyEmployee Class

A concrete class for employees paid by the hour, with overtime logic.

java
public class HourlyEmployee extends Employee {
    private double hourlyRate;
    private double hoursWorked;

    public HourlyEmployee(String employeeId, String name, double hourlyRate, double hoursWorked) {
        super(employeeId, name);
        this.hourlyRate = hourlyRate;
        this.hoursWorked = hoursWorked;
    }

    @Override
    public double calculatePay() {
        if (hoursWorked <= 40) {
            return hourlyRate * hoursWorked;
        } else {
            double regularPay = hourlyRate * 40;
            double overtimeHours = hoursWorked - 40;
            double overtimePay = overtimeHours * hourlyRate * 1.5;
            return regularPay + overtimePay;
        }
    }
}
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.