Subclasses & Extends, Pt. 2 (Extending)
Overview of Subclassing and Behavior Extension
In object-oriented programming, subclasses allow the extension of behaviors and fields from a superclass.
Focusing on behavior allows for the addition of specific methods relevant to the subclass.
Example: Private Plane Behavior
When defining a subclass such as
PrivatePlane, new unique methods can be added:Example method:
bringWarmTowels.
This method is specific to
PrivatePlaneand not found in the generalAirplaneclass.
Instantiation of a Private Plane
Declaring a private plane object:
Syntax:
PrivatePlane pp = new PrivatePlane();
Calling the specific method:
pp.bringWarmTowels();executes successfully, showcasing inheritance of behavior.
Type Declaration and Access
Declaring variables as the superclass restricts access to subclass-specific methods:
Example:
Airplane luxPlane = new PrivatePlane();does not allow callingluxPlane.bringWarmTowels();
The declared type (
Airplane) must have the method implemented, which it does not.Attempting to call non-existent methods results in errors (e.g., red squiggle in IntelliJ).
Creating the PrivatePlane Class in IntelliJ
Class creation involves extending the superclass:
Syntax:
class PrivatePlane extends Airplane.
An empty
PrivatePlaneclass can still function, leveraging inherited methods fromAirplane.Inherited methods from
Airplanecan be called without needing implementations inPrivatePlaneitself.Example: Calling
pp.fly();works even whenPrivatePlaneis empty.
Implementation of New Method in PrivatePlane
Adding specific methods to
PrivatePlaneenhances its functionality:Implementation of
bringWarmTowels:public void bringWarmTowels() { System.out.println("Here is your warm towel."); }
Calling this method:
After implementation,
pp.bringWarmTowels();shows the method as bold in IntelliJ, indicating it exists.
Output confirmed through console:
"Here is your warm towel."
Luxurious Takeoff Method
Creating specialized methods that require specific types:
Example method:
luxuryTakeoffthat takes aPrivatePlaneas a parameter.Uses the inherited
takeoffmethod along withbringWarmTowels.
Method signature:
public void luxuryTakeoff(PrivatePlane plane).
Invoking the method:
luxuryTakeoff(pp);works due to the matching type.
Limitations on Parameter Passing
Attempting to pass a superclass type to methods expecting subclass types fails:
Example: Trying to pass
Airplane planytoluxuryTakeoffwill not work.
Reasons for limitation:
Airplanelacks access tobringWarmTowels, differentiating it fromPrivatePlanedespite other shared behaviors.
Summary of substitution principle:
Superclass instances cannot take the place of subclass instances, maintaining the integrity of specialized behaviors.