Skip to content

Java Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to design software and applications. It models real-world entities by bundling data (attributes) and behaviors that operate on the data (methods) together. Java is a purely object-oriented language, and all code must exist within classes.

The core ideas of OOP mainly revolve around four fundamental principles:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

1. Encapsulation

Encapsulation refers to bundling an object's data (attributes) and the code that operates on the data (methods) into a single independent unit (i.e., a "class"). It also implements data hiding, which restricts external direct access to an object's internal data.

In Java, encapsulation is typically achieved through:

  • Declaring class attributes as private, so they cannot be accessed directly by external classes.
  • Providing public getter and setter methods to read and modify these private attributes. This allows us to add control logic (such as validation) when modifying data.
java
public class Person {
    // 1. Make attributes private
    private String name;
    private int age;

    // 2. Provide public getter methods to access data
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    // 3. Provide public setter methods to modify data with control logic
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        if (age > 0 && age < 150) { // Data validation
            this.age = age;
        } else {
            System.out.println("Invalid age value!");
        }
    }
}

// In other classes
Person person = new Person();
// person.name = "John"; // Compilation error! Cannot access private attribute directly
person.setName("John");
person.setAge(30);
System.out.println("Name: " + person.getName());

Advantages:

  • Security: Protects data from accidental or malicious modification.
  • Flexibility: The internal implementation of a class can be freely modified without affecting external code that uses the class.
  • Maintainability: Code is easier to understand and maintain.

2. Inheritance

Inheritance is a mechanism that allows one class (called the subclass or derived class) to acquire the attributes and methods of another class (called the superclass or base class). Subclasses can reuse parent class code and can add their own new features or override parent class methods.

In Java, the extends keyword is used to implement inheritance.

java
// Parent class
class Animal {
    public void eat() {
        System.out.println("This animal is eating...");
    }
}

// Subclass Dog inherits from Animal
class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking!");
    }
}

// Usage
Dog myDog = new Dog();
myDog.eat();  // Call method inherited from parent class
myDog.bark(); // Call subclass's own method

Advantages:

  • Code Reuse: Avoids code redundancy.
  • Clear Structure: Establishes "is-a" relationships between classes, conforming to real-world logic.

3. Polymorphism

Polymorphism (literally meaning "many forms") allows us to treat objects of different types in a unified way. It refers to the ability of a parent class reference to point to any of its subclass objects, and when calling the same method, different behaviors are executed based on the actual type of the object.

Implementing polymorphism typically requires two conditions:

  1. Inheritance: There must be an inheritance relationship.
  2. Method Overriding: Subclasses redefine methods with the same name from the parent class.
java
class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override // Annotation indicates this is method overriding
    public void makeSound() {
        System.out.println("Woof!");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Animal myAnimal; // Parent class reference

        myAnimal = new Dog(); // Points to Dog object
        myAnimal.makeSound();   // Executes Dog's makeSound() -> Output: Woof!

        myAnimal = new Cat(); // Points to Cat object
        myAnimal.makeSound();   // Executes Cat's makeSound() -> Output: Meow!
    }
}

Advantages:

  • Flexibility and Extensibility: New subclasses can be easily added without modifying existing code that handles these objects.

4. Abstraction

Abstraction refers to hiding complex implementation details and showing only the necessary functionality to users. It helps us manage complexity.

In Java, abstraction can be achieved through Abstract Classes and Interfaces.

  • Abstract Class: A class that cannot be instantiated and may contain abstract methods (methods without a body). It serves as a base class for other classes, forcing subclasses to implement its abstract methods.
  • Interface: A completely abstract "class" that contains only abstract methods and constants. A class can implement multiple interfaces, thereby gaining multiple behavioral capabilities.
java
// Abstract class
abstract class Shape {
    // Abstract method, no body
    public abstract double getArea();

    public void printInfo() {
        System.out.println("This is a shape.");
    }
}

class Circle extends Shape {
    private double radius;
    // ... constructor ...

    // Must implement parent's abstract method
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

We will explore inheritance, abstract classes, and interfaces in more detail in subsequent chapters.

Content is for learning and research only.