Abstract Classes

Abstract Class

  • An abstract class serves as a middle ground between a regular class and an interface.

  • Key Characteristics:

    • Cannot be instantiated (no objects can be created directly from it).

    • Can contain both methods and fields.

Example: Bird Class

  • Bird Class:

    • Methods:

      • takeoff: Provides implementation for takeoff behavior.

      • land: Provides implementation for landing behavior.

      • fly:

        • Declared as an abstract method (no implementation provided).

        • Subclasses must implement this method.

        • Written as: abstract void fly();

  • Subclassing:

    • Classes like Hawk and Hummingbird extend the Bird class.

    • Each subclass is responsible for providing an implementation for the fly method.

    • Example Usage:

      • Bird b = new Hummingbird();

Responsibilities of Subclasses

  • When subclassing from an abstract class:

    • Implement any abstract methods defined in the parent class.

    • E.g., Hawk might implement fly as "swoops and glides" and Hummingbird as "hovers".

Practical Implementation in IntelliJ

  • Changes to implement abstract methods:

    • Mark the Bird class as abstract.

    • Define fly as an abstract method (remove its body and use a semicolon).

  • Instantiation Challenges:

    • Direct instantiation of an abstract class causes errors; ensure to instantiate subclass objects instead.

Instantiation of Subclasses

  • Hawk Class:

    • Implements the fly method (e.g., swooping behavior).

  • Hummingbird Class:

    • Implements the fly method (e.g., hovering behavior).

Substitutability Rules

  • Substitutability allows us to call methods like fly, takeoff, and land on subclasses of Bird.

  • Example of method calls:

    • hawk.fly(), hawk.takeoff(), and hawk.land() will work seamlessly as

    • These calls utilize inherited methods from the abstract class.

Conclusion

  • Abstract classes are crucial for defining categories of objects that share common behaviors while enforcing specific implementations in subclasses.