← Back to Home

Module 2: Advanced OOP Concepts

Module Overview

Explore advanced object-oriented programming concepts and best practices.

Learning Objectives

Inheritance and Polymorphism in Detail

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. Polymorphism enables objects to be treated as instances of their parent class while maintaining their unique implementations.

Key Inheritance Concepts:

  • Superclass and Subclass:
    • A superclass (or parent class) is a class that is inherited from
    • A subclass (or child class) is a class that inherits from a superclass
    • The "extends" keyword creates an inheritance relationship
  • Method Overriding:
    • When a subclass provides a specific implementation for a method already defined in the superclass
    • The overridden method must have the same name, return type, and parameters
    • The @Override annotation helps prevent errors
  • Access Modifiers in Inheritance:
    • public: accessible from anywhere
    • protected: accessible within the same package and by subclasses
    • private: accessible only within the declaring class
    • default (no modifier): accessible only within the same package

Inheritance Implementation Example:

// Superclass
public class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void makeSound() {
        System.out.println("Some generic sound");
    }
}

// Subclass
public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name); // Call to superclass constructor
        this.breed = breed;
    }
    
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
    
    // Call superclass version of overridden method
    public void makeAnimalSound() {
        super.makeSound();
    }
}

// Polymorphic usage
Animal myPet = new Dog("Rex", "German Shepherd");
myPet.makeSound(); // Outputs: "Woof!"

Abstract Classes and Methods:

  • An abstract class cannot be instantiated and may contain abstract methods
  • An abstract method is declared without implementation
  • Subclasses must implement all abstract methods unless they are also abstract
  • Example:
    public abstract class Shape {
        public abstract double area();
        public abstract double perimeter();
    }
    
    public class Circle extends Shape {
        private double radius;
        
        public Circle(double radius) {
            this.radius = radius;
        }
        
        @Override
        public double area() {
            return Math.PI * radius * radius;
        }
        
        @Override
        public double perimeter() {
            return 2 * Math.PI * radius;
        }
    }

Resources