OOPs Concepts in Java with Examples

Introduction

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and methods. The four main principles of OOP are abstraction, encapsulation, inheritance, and polymorphism. Advanced OOP concepts include composition, aggregation, association, cohesion, coupling, and delegation. These principles and concepts help in building modular, reusable, and maintainable software.

Table of Contents

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
  5. Advanced OOP Concepts
    • Composition
    • Aggregation
    • Association
    • Cohesion
    • Coupling
    • Delegation
OOPs Concepts in Java with Examples

1. Abstraction in Java with Example

Abstraction is the process of hiding the implementation details and showing only the functionality to the user. It reduces complexity by hiding unnecessary details from the user.

Example:

abstract class Vehicle {
    abstract void start();
}

class Car extends Vehicle {
    @Override
    void start() {
        System.out.println("Car starts with key ignition");
    }
}

class Bike extends Vehicle {
    @Override
    void start() {
        System.out.println("Bike starts with kick start");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle car = new Car();
        Vehicle bike = new Bike();
        car.start(); // Output: Car starts with key ignition
        bike.start(); // Output: Bike starts with kick start
    }
}

Real-World Example:

Consider an ATM machine where users interact with the machine to perform transactions without knowing the internal processing.

2. Encapsulation in Java with Example

Encapsulation is the process of wrapping data (variables) and code (methods) together as a single unit. It restricts direct access to some of the object's components, which can prevent the accidental modification of data.

Example:

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setAge(30);
        System.out.println("Name: " + person.getName()); // Output: Name: John
        System.out.println("Age: " + person.getAge()); // Output: Age: 30
    }
}

Real-World Example:

In a banking application, account details should be encapsulated to prevent unauthorized access and modification.

3. Inheritance in Java with Example

Inheritance is the mechanism in which one class acquires the properties and behaviors of another class. It helps in code reusability and method overriding.

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Output: This animal eats food.
        dog.bark(); // Output: The dog barks.
    }
}

Real-World Example:

In an organization, an Employee class can inherit from a Person class to reuse the common properties and methods.

4. Polymorphism in Java with Example

Polymorphism allows methods to do different things based on the object it is acting upon. It can be achieved through method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

Example:

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.makeSound(); // Output: Dog barks
        myCat.makeSound(); // Output: Cat meows
    }
}

Real-World Example:

A payment processing system where different payment methods such as credit card, debit card, and PayPal have different processing steps.

5. Advanced OOP Concepts

Composition in Java with Example

Composition is a design principle where a class is composed of one or more objects of other classes. It is a strong type of association with a whole-part relationship.

Example:

class Engine {
    void start() {
        System.out.println("Engine starts.");
    }
}

class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }

    public void start() {
        engine.start();
        System.out.println("Car starts.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start(); // Output: Engine starts. Car starts.
    }
}

Real-World Example:

A Computer class that contains CPU, RAM, and HardDrive objects.

Aggregation in Java with Example

Aggregation is a type of association that represents a whole-part relationship where the part can exist independently of the whole.

Example:

class Employee {
    private String name;

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

    public String getName() {
        return name;
    }
}

class Department {
    private String name;
    private List<Employee> employees;

    public Department(String name) {
        this.name = name;
        this.employees = new ArrayList<>();
    }

    public void addEmployee(Employee employee) {
        employees.add(employee);
    }

    public void showEmployees() {
        for (Employee employee : employees) {
            System.out.println("Employee: " + employee.getName());
        }
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp1 = new Employee("John Doe");
        Employee emp2 = new Employee("Jane Smith");

        Department dept = new Department("IT Department");
        dept.addEmployee(emp1);
        dept.addEmployee(emp2);

        System.out.println("Department: " + dept.getName());
        dept.showEmployees();
        // Output:
        // Department: IT Department
        // Employee: John Doe
        // Employee: Jane Smith
    }
}

Real-World Example:

A Library class aggregating Book objects.

Association in Java with Example

Association is a relationship between two classes that establishes a connection between their objects.

Example:

class Address {
    private String street;
    private String city;

    public Address(String street, String city) {
        this.street = street;
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public String getCity() {
        return city;
    }
}

class Person {
    private String name;
    private Address address;

    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public Address getAddress() {
        return address;
    }
}

public class Main {
    public static void main(String[] args) {
        Address address = new Address("123 Main St", "Springfield");
        Person person = new Person("John Doe", address);

        System.out.println("Person: " + person.getName());
        System.out.println("Address: " + person.getAddress().getStreet() + ", " + person.getAddress().getCity());
        // Output:
        // Person: John Doe
        // Address: 123 Main St, Springfield
    }
}

Real-World Example:

A Person class associated with an Address class.

Cohesion in Java with Example

Cohesion refers to how closely related and focused the responsibilities of a single module or class are.

Example:

public class Employee {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class SalaryCalculator {
    public double calculateAnnualSalary(Employee employee) {
        return employee.getAge() * 1000; // Example calculation
    }
}

public class Main {
    public static void main(String[] args) {
        Employee employee = new Employee("John", 30);
        SalaryCalculator calculator = new SalaryCalculator();
        System.out.println("Annual Salary: " + calculator.calculateAnnualSalary(employee));
        // Output: Annual Salary: 30000.0
    }
}

Real-World Example:

A Book class that has attributes like title and author, focusing on book-related

properties.

Coupling in Java with Example

Coupling refers to the degree of direct knowledge that one class has about another class.

Example:

class Engine {
    public void start() {
        System.out.println("Engine started.");
    }
}

class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }

    public void start() {
        engine.start();
        System.out.println("Car started.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start(); // Output: Engine started. Car started.
    }
}

Real-World Example:

A Printer class directly interacting with PaperTray class.

Delegation in Java with Example

Delegation is a design pattern where an object delegates responsibility for a task to another object.

Example:

interface TravelBooking {
    void bookTicket();
}

class TrainBooking implements TravelBooking {
    @Override
    public void bookTicket() {
        System.out.println("Train ticket booked.");
    }
}

class AirBooking implements TravelBooking {
    @Override
    public void bookTicket() {
        System.out.println("Flight ticket booked.");
    }
}

class TicketBookingByAgent implements TravelBooking {
    private TravelBooking travelBooking;

    public TicketBookingByAgent(TravelBooking travelBooking) {
        this.travelBooking = travelBooking;
    }

    @Override
    public void bookTicket() {
        travelBooking.bookTicket();
    }
}

public class Main {
    public static void main(String[] args) {
        TicketBookingByAgent agent = new TicketBookingByAgent(new TrainBooking());
        agent.bookTicket(); // Output: Train ticket booked.

        agent = new TicketBookingByAgent(new AirBooking());
        agent.bookTicket(); // Output: Flight ticket booked.
    }
}

Real-World Example:

A travel agent delegating the actual booking process to specific booking classes like TrainBooking and AirBooking.

Conclusion

Understanding and implementing OOP concepts like abstraction, encapsulation, inheritance, and polymorphism, along with advanced concepts like composition, aggregation, association, cohesion, coupling, and delegation, are crucial for building robust and maintainable Java applications. By mastering these principles, developers can create more modular, reusable, and flexible code.

Happy coding!

Comments