Inheritance in OOPS -- Object Oriented Programming - Java


Index

  1. 1. Inheritance in Object-Oriented Design
  2. 2. Design Patterns Introduction and Classification
  3. 3. Iterator Pattern

1. Inheritance in Object-Oriented Design:

Inheritance allows one class (called the subclass or derived class) to inherit the fields and methods of another class (called the superclass or base class). This promotes code reuse and establishes a natural hierarchy between classes.

Key Concepts:

Example:

class Animal {
    protected String name;

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

class Dog extends Animal {  // Inherits from Animal
    public Dog(String name) {
        this.name = name;  // Inherited from Animal
    }

    @Override
    public void eat() {
        System.out.println(name + " eats dog food.");  // Overridden method
    }
}

In this example:

Benefits of Inheritance:

2. Design Patterns: Introduction and Classification

Design patterns are typical solutions to common problems in software design. They represent best practices and provide general templates that can be applied to solve recurring design challenges.

Introduction to Design Patterns:
Classification of Design Patterns:
  1. Creational Patterns:

    • Focus on how objects are created.
    • Example: Factory Pattern, Singleton Pattern.
  2. Structural Patterns:

    • Deal with object composition, forming larger structures.
    • Example: Adapter Pattern, Composite Pattern.
  3. Behavioral Patterns:

    • Focus on how objects interact with one another.
    • Example: Observer Pattern, Iterator Pattern.

3. Iterator Pattern:

The Iterator pattern is a behavioral design pattern that provides a way to access elements of a collection (like a list or array) sequentially without exposing the underlying representation.

Why Use the Iterator Pattern?

Example:

import java.util.Iterator;
import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Cat");
        animals.add("Dog");
        animals.add("Cow");

        // Using an iterator to traverse the collection
        Iterator<String> iterator = animals.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

In this example:

Benefits of the Iterator Pattern: