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
flymethod.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
flyas "swoops and glides" and Hummingbird as "hovers".
Practical Implementation in IntelliJ
Changes to implement abstract methods:
Mark the Bird class as abstract.
Define
flyas 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
flymethod (e.g., swooping behavior).
Hummingbird Class:
Implements the
flymethod (e.g., hovering behavior).
Substitutability Rules
Substitutability allows us to call methods like
fly,takeoff, andlandon subclasses of Bird.Example of method calls:
hawk.fly(),hawk.takeoff(), andhawk.land()will work seamlessly asThese 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.