Unit 3 - Notes

CSE310

Unit 3: Inheritance and Polymorphism

1. Inheritance

Inheritance is a fundamental mechanism in object-oriented programming (OOP) that allows a new class to acquire the properties (fields) and behaviors (methods) of an existing class. It promotes code reusability and establishes an "IS-A" relationship between classes.

Key Terminology

  • Superclass (Parent/Base Class): The class whose features are inherited.
  • Subclass (Child/Derived Class): The class that inherits from the superclass.
  • extends keyword: Used to establish inheritance in Java.

Types of Inheritance in Java

  1. Single Inheritance: A subclass inherits from only one superclass.
  2. Multilevel Inheritance: A chain of inheritance (e.g., Class C extends Class B, Class B extends Class A).
  3. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
  4. Multiple Inheritance: Java does not support multiple inheritance with classes (to avoid the "Diamond Problem") but supports it via Interfaces.

A UML-style class diagram illustrating three types of inheritance side-by-side. Panel 1: "Single Inh...
AI-generated image — may contain inaccuracies

Syntax and Example

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

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

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();  // Inherited method
        myDog.bark(); // Specialized method
    }
}


2. Method Overriding

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It is used to achieve Runtime Polymorphism.

Rules for Overriding

  1. The method name must be the same as in the parent class.
  2. The argument list (parameters) must be identical.
  3. The return type must be the same or a covariant type (a subclass of the original return type).
  4. Access modifiers cannot be more restrictive (e.g., if parent is protected, child cannot be private).
  5. Use the @Override annotation to ensure compiler checks.

Overloading vs. Overriding

Feature Method Overloading Method Overriding
Scope Within the same class. Across Parent-Child classes.
Signature Must have different parameters. Must have identical parameters.
Binding Static (Compile-time). Dynamic (Run-time).

3. The super and final Keywords

The super Keyword

The super reference variable is used to refer to the immediate parent class object.

  • Accessing Parent Methods: super.methodName() (Useful when the child overrides the method but still needs the parent's logic).
  • Accessing Parent Variables: super.variableName (Useful if the child hides the variable).
  • Invoking Parent Constructor: super() must be the first statement in the child constructor.

A conceptual diagram visualizing "Constructor Chaining" in Java. Show a vertical stack of three bloc...
AI-generated image — may contain inaccuracies

The final Keyword

The final keyword is used to restrict the user.

  1. Final Variable: Becomes a constant. Value cannot be changed once initialized.
  2. Final Method: Cannot be overridden by subclasses.
  3. Final Class: Cannot be inherited (cannot have subclasses).

JAVA
class Parent {
    final void display() {
        System.out.println("Final method.");
    }
}

class Child extends Parent {
    // void display() { } // COMPILE ERROR: Cannot override final method
}


4. The Object Class

The java.lang.Object class is the root of the class hierarchy. Every class in Java has Object as a superclass.

Overriding toString()

  • Default Behavior: Returns a string consisting of the class name, the @ symbol, and the hash code (e.g., Student@15db9742).
  • Purpose of Override: To provide a meaningful string representation of the object (e.g., values of its fields).

JAVA
@Override
public String toString() {
    return "Student [name=" + name + ", age=" + age + "]";
}

Overriding equals()

  • Default Behavior: Compares object references (memory addresses), similar to ==.
  • Purpose of Override: To compare the contents (state) of objects.

Contract for equals():

  1. Check if this == obj (Same reference).
  2. Check if obj is null or classes mismatch.
  3. Cast obj to the specific class type.
  4. Compare significant fields.

5. Polymorphism and instanceof

Runtime Polymorphism (Dynamic Method Dispatch)

Polymorphism allows an object to take on many forms. In Java, this is most commonly seen when a Superclass reference holds a Subclass object. The method called is determined by the actual object instance at runtime, not the reference type.

JAVA
Animal a = new Dog(); // Upcasting
a.makeSound(); // Calls Dog's version of makeSound

The instanceof Operator

Used to test whether an object is an instance of a specified type (class, subclass, or interface). It returns true or false. It is crucial when downcasting to avoid ClassCastException.

JAVA
if (a instanceof Dog) {
    Dog d = (Dog) a; // Safe Downcasting
    d.bark();
}


6. Abstract Methods and Abstract Classes

Abstraction is the process of hiding implementation details and showing only functionality to the user.

Abstract Class

  • Declared using abstract keyword.
  • Cannot be instantiated (cannot do new AbstractClass()).
  • Can have constructors and static methods.
  • Can contain both abstract methods (no body) and concrete methods (with body).

Abstract Method

  • Declared without an implementation (no braces {}).
  • Must be implemented by the first concrete subclass.

JAVA
abstract class Shape {
    abstract void draw(); // Abstract method
    
    void info() { // Concrete method
        System.out.println("This is a shape.");
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

A comparative illustration between an Abstract Class and a Concrete Class. On the left, a box labele...
AI-generated image — may contain inaccuracies


7. Interfaces

An interface is a reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It is a blueprint of a class.

Key Characteristics

  • Declared using the interface keyword.
  • Variables are implicitly public static final.
  • Methods are implicitly public abstract (prior to Java 8).
  • A class uses implements to inherit an interface.
  • Multiple Inheritance: A class can implement multiple interfaces (implements A, B).

Java 8 Enhancements: Static and Default Methods

Prior to Java 8, interfaces could not have method bodies. Java 8 introduced:

  1. Default Methods: Methods defined with the default keyword inside an interface.

    • Purpose: Allows adding new methods to interfaces without breaking existing classes that implement the interface.
    • Can be overridden by the implementing class.

    JAVA
        interface Vehicle {
            void clean(); // Abstract
            
            default void start() { // Default method
                System.out.println("Vehicle starting...");
            }
        }
        

  2. Static Methods: Helper methods associated with the interface, not the object.

    • Called using InterfaceName.methodName().

A Venn diagram comparing "Abstract Class" vs "Interface" (Java 8+). Left Circle (Abstract Class): "e...
AI-generated image — may contain inaccuracies