Concepts / Working with Inheritance and Polymorphism

Working with Inheritance and Polymorphism

A class is a template; an object is an instance of that template with its own state.

  • Programming

From Template to Object

Imagine designing a system that must represent several similar things. Each thing may need the same kinds of data and actions, but each individual thing can hold different data. A class provides the reusable template for that design. An object is an instance of the class with its own state. This distinction is the starting point for understanding inheritance and polymorphism.

creates instancecreates instanceClass templateattributes and methodsObject Astate AObject Bstate B
How does one class template produce multiple objects with independent attribute values?

The class describes the common structure and behavior. Each object produced from that class is an individual instance with its own state. Therefore, two objects can come from the same template while holding different attribute values. The template is shared as a design; the objects are the individual entities that carry their own state.

Two Accounts from One Template

Model two accounts using one Account class template.

Identify the template: The Account class describes the attributes and methods that an account object can have.

Create the first object: Account A is an instance of the class with its own state, such as one account holder and one balance.

Create the second object: Account B is another instance of the same class. It follows the same template but can contain different attribute values.

Compare the objects: Both objects have the class's structure and behavior, but their individual states are not required to be identical.

One class can describe multiple objects while each object maintains its own state.

Data and Behavior

A class has two core components: attributes and methods. Attributes store data. Methods define behavior. In a conceptual design for a library item, attributes might represent information about the item, while methods might represent actions the item can perform. The important distinction is that attributes describe stored data, whereas methods describe what the object does.

containscontainsClasstemplateAttributesstored dataMethodsdefined behavior
Which parts of a class represent stored data, and which parts represent actions?
Class componentRoleConceptual example
AttributeStores dataA library item's title
MethodDefines behaviorAn action performed by the library item

Attributes describe stored information; methods describe behavior.

When analyzing a class, ask two questions: What information must each object store? What behavior must each object provide? The first question points toward attributes; the second points toward methods.

The Object Lifecycle

Objects have a lifecycle that includes creation, use, and eventual destruction. A constructor initializes an object when it is created. Initialization gives the new object its starting state. A destructor performs cleanup before the object is destroyed. Destructors are rarely needed, so they should be understood as part of the lifecycle without being treated as a routine requirement for every class.

after initializationbefore destructionthenObject createdconstructor initializesstateObject usedmethods provide behaviorCleanupdestructor may clean upObject destroyed
What happens to an object from creation through use and eventual destruction?

Tracing a Document Object

Trace the conceptual lifecycle of a document object.

Construction: The document object is created and its constructor initializes its starting state.

Use: The object remains available while its methods provide the behavior defined by its class.

Destruction: Before the object is destroyed, its destructor can perform cleanup. This step is included in the lifecycle, although destructors are rarely needed.

Construction establishes initial state, use applies behavior, and destruction follows any needed cleanup.

Extending a Parent Class

Inheritance allows a child class to extend a parent class. The child can reuse code from the parent and specialize that design for a more specific purpose. This creates a parent-child relationship between classes: the parent provides an existing foundation, while the child builds on it rather than starting from nothing.

extendsprovidesadds or specializesParent classreusable foundationChild classextended and specializeddesignReused codefrom parentSpecialized codeadded by child
What does a child class receive from a parent class, and what can it add or specialize?

A General Item and a Specialized Item

Design a general Item class and a more specific DigitalItem child class.

Create the parent: The Item class provides the general structure and behavior shared by items.

Extend the parent: DigitalItem is created as a child class that extends Item rather than duplicating the entire design.

Reuse the foundation: The child class can reuse relevant code from the parent class.

Specialize the child: DigitalItem can add or specialize behavior for its more specific purpose.

Inheritance supports reuse while allowing a child class to provide a more specialized design.

Inheritance is not merely a way to create a second class. Its value is the relationship between the classes: the child extends an existing parent, reuses code, and specializes the result.

One Interface, Different Behavior

Polymorphism describes a situation in which the same method call can produce different behavior depending on the object's actual type. The caller can work through a shared method or interface, while different object types provide their own implementations of that behavior. This is useful when several related classes should respond to the same kind of request in type-specific ways.

on Type Aon Type Bproducesproducesperform actionshared method callType Aimplementation ABehavior AType Bimplementation BBehavior B
How can the same method call produce different behavior according to the object's actual type?

A Shared Notification Request

Use one shared request for two notification object types.

Define the shared behavior: The related notification types support a common method request such as sending a notification.

Use the request: A caller makes the same method call without needing to describe every type-specific implementation.

Select the object's behavior: The actual notification type determines which implementation responds to the call.

Observe polymorphism: The request is shared, but the resulting behavior differs according to the object's actual type.

Polymorphism separates the shared request from the type-specific behavior that fulfills it.

Mistakes to Avoid

  • Treating a class and an object as the same thing.

    A class is the template, while an object is an instance of that template with its own state.

    Fix: Use class for the reusable design and object for each individual instance.

  • Confusing attributes with methods.

    Attributes store data; methods define behavior.

    Fix: Ask whether the class must remember information or perform an action.

  • Assuming every class needs a destructor.

    Destructors clean up before destruction but are rarely needed.

    Fix: Understand the destructor's lifecycle role without assuming it is required in every design.

  • Using inheritance only to duplicate a class.

    Inheritance is intended to let child classes extend parent classes while reusing and specializing code.

    Fix: Identify the reusable parent foundation and the specific behavior the child adds or specializes.

  • Assuming polymorphism means every object behaves identically.

    Polymorphism allows the same method call to produce different behavior depending on the object's actual type.

    Fix: Separate the shared request from each type's implementation.

Check Your Understanding

MEDIUM

A school system needs several kinds of school records. Each record has stored data, shared behavior, and some type-specific behavior. Explain which part should be represented by a class, which parts are attributes and methods, where a constructor fits, and when inheritance or polymorphism would be useful.

Hints
  • Start by describing the common template and the individual record objects.
  • Classify stored information as attributes and actions as methods.
  • Place initialization at object creation and cleanup before destruction.
  • Use inheritance for a parent-child design with reused and specialized code.
  • Use polymorphism when related object types respond differently to one shared method call.

What do you think happens?

A parent class defines shared behavior, and two child classes specialize that behavior. If the same method request is made through the shared interface, should both objects necessarily produce identical behavior?

  • Yes, because the method name is the same
  • No, the actual object type can determine different behavior
Reveal answer

Answer: No, the actual object type can determine different behavior.

Polymorphism allows a shared method call to produce different behavior depending on the object's actual type.

Key Takeaways

  • A class is a template, while an object is an instance of that template with its own state.
  • Attributes store data and methods define behavior; both are core components of a class.
  • Constructors initialize objects, while destructors clean up before destruction and are rarely needed.
  • Inheritance lets child classes extend parent classes, reuse code, and specialize a design.
  • Polymorphism allows one shared method call to produce different behavior for different object types.