DoAssignment study guide

A2.2 · Apply encapsulation, inheritance and polymorphism

Learn to apply encapsulation, inheritance and polymorphism through clear examples and targeted practice.

Ontario Grade 12 Computer Science

Programming Concepts and Skills

Applying three object-oriented ideas in Python 3

In ICS3U, you learned that a class describes objects and that objects can contain attributes and methods. This lesson builds on that knowledge by applying encapsulation, inheritance, and polymorphism. Each describes a different part of a class design: encapsulation concerns how a class manages its data; inheritance describes a relationship between a general class and a more specific one; and polymorphism describes how the same method call can lead to behaviour suited to different object types. The Python examples are for reading and tracing. They are not claims that the code was run.

What you will learn

  • Explain how encapsulation keeps data and the methods that manage it together.
  • Identify a parent class and subclass and describe what the subclass reuses or changes.
  • Trace how different objects respond to the same method call.
  • Apply encapsulation, inheritance, and polymorphism in short class designs and code traces.

1. Prerequisite review and encapsulation

A class describes a kind of object. It can define attributes, which store information, and methods, which describe actions. An object is a particular instance of a class. For example, a Book class could define a page count and a method for changing it; an object could represent one particular book.
Encapsulation means keeping related data and the methods that manage that data together in a class. The class can provide methods as the intended way for other parts of a program to use or change important data. A method can check a requested change and accept it only when it meets a rule. The class should also establish suitable starting data when an object is created; checking only later changes would leave the initial data unchecked.
In Python, a name beginning with an underscore, such as `_pages`, is a convention indicating that the attribute is intended for internal use. It does not make the value strictly inaccessible. The design point is that callers should use the class's methods as intended, rather than changing internal data without the class's checks. Apply control where an unrestricted change could leave an object with unsuitable data.
When designing an encapsulated class, state the rule for its data, establish a suitable initial value, and provide a method for later changes when needed. In the first example, the rule is that the page count must be a positive integer. Python treats Boolean values as related to integers, so the code uses `type(value) is int` to exclude `True` and `False` as well as rejecting zero and negative numbers.
  • A class groups related attributes and methods.
  • Encapsulation gives a class responsibility for managing its data, including suitable starting values and changes.
  • A leading underscore in Python is a convention, not strict privacy.
  • Check the initial value and later changes against the same rule.

2. Inheritance: reuse and specialize

Inheritance lets one class be based on another. The more general class is the parent or base class; the more specific class is the child or subclass. A subclass can reuse the parent's available attributes and methods, then add information or behaviour that suits its more specific purpose.
Choose inheritance when the relationship makes sense as a kind-of relationship. An Ebook is a kind of LibraryItem, so an Ebook subclass can reuse a LibraryItem's title information and add a file format. A subclass can also define a method with the same name as a parent method to provide its own version. This is called overriding.
Before using inheritance, identify what the classes have in common and what the subclass adds or adapts. The parent should represent the shared idea, not just be a convenient place to put unrelated code. A clear relationship makes it easier to understand what an object can do.
In Python, a subclass names its parent in parentheses in the class definition. The `super()` call in the example asks the parent class to perform its title setup. The subclass then stores its additional format. The diagram summarizes the relationship and responsibilities shown in that example.
  • A subclass is a more specific kind of its parent class.
  • A subclass can reuse parent behaviour and add or adapt its own.
  • An overridden method supplies a subclass-specific version of a parent method.

3. Polymorphism: one method call, different responses

Polymorphism means that objects of different classes can respond to the same method call in different ways. For instance, a Book and an Ebook can both provide a `display_info` method. A program can make that same request for either object; the object's class determines the response.
To trace polymorphism, follow each object separately. First identify its class. Then identify the method implementation that class provides, including an overridden version if there is one. Finally, determine the result of that method for the object's data. Do not assume that every object in a collection uses one identical implementation.
The three ideas can appear together. Encapsulation assigns data management to a class. Inheritance lets a more specific class reuse or adapt a general class. Polymorphism lets a caller use a shared method name while the objects supply responses suited to their classes. When reviewing a design, ask what data each class manages, which class relationship is intended, and which method responds to each call.
The examples state their inputs and conditions, then trace the expected results rather than claiming the code was executed. When practising, write down the object, its class, the method used, and the result for each call.
  • A shared method name lets a caller make the same kind of request to different objects.
  • The object's class determines the method behaviour used.
  • Trace object type, method implementation, and result for every call.

Worked example

Control changes to a page count

A Book object starts with 180 pages. A caller requests 220 pages and then 0 pages. Use a method that accepts only positive integers, excluding Boolean values. Trace the changes and state the expected final page count.
A method manages Book data
sets valid starting valuupdates only if validBook: page dataConstructor checks startSetter checks change

The constructor establishes starting data, and the setter checks later changes.

Python 3

class Book:
    def __init__(self, pages):
        if type(pages) is not int or pages <= 0:
            raise ValueError("pages must be a positive integer")
        self._pages = pages

    def set_pages(self, value):
        if type(value) is int and value > 0:
            self._pages = value

    def get_pages(self):
        return self._pages

book = Book(180)
book.set_pages(220)
book.set_pages(0)
print(book.get_pages())
  1. State the rule and inputs
    The constructor and setter both accept a value only if its type is exactly `int` and it is greater than zero. This deliberately excludes Python Boolean values. The input is an initial value of 180 followed by requests for 220 and 0. The object starts with suitable data, and the method changes the stored value only when a request meets the rule.
  2. Trace the requests
    The starting value is 180. The request for 220 meets the rule, so the stored value becomes 220. The request for 0 does not meet the rule, so the method leaves the stored value unchanged. The expected final value is 220 pages, and the expected printed output is `220`.
Answer: The expected final page count is 220. Both object creation and the method for changing the count check that the value is a positive integer, excluding Boolean values.
Check: The class controls the starting value and later changes. In Python, `_pages` signals intended internal use by convention; the method supplies the checked way to make a change.

Worked example

Reuse a library item's shared information

A LibraryItem has a title. An Ebook is a kind of LibraryItem and also has a file format. Show how an Ebook can reuse the title setup and provide its own display method. Trace an Ebook with title “Forest Notes” and format “EPUB”.
LibraryItem and Ebook
inherits fromLibraryItem: title and dEbook: format and displa

Ebook is based on LibraryItem; it reuses the title and adds a format.

Python 3

class LibraryItem:
    def __init__(self, title):
        self.title = title

    def display_info(self):
        return self.title

class Ebook(LibraryItem):
    def __init__(self, title, file_format):
        super().__init__(title)
        self.file_format = file_format

    def display_info(self):
        return self.title + " (" + self.file_format + ")"

ebook = Ebook("Forest Notes", "EPUB")
print(ebook.display_info())
  1. Separate shared and specific information
    A title belongs to both general library items and ebooks, so LibraryItem manages it. The file format is specific to Ebook in this example, so Ebook adds that attribute and defines the display behaviour it needs.
  2. Trace object creation and display
    The inputs are the title “Forest Notes” and format “EPUB”. Creating the Ebook initializes the title through the parent class and stores the format in the subclass. Calling `display_info` uses the Ebook version, which combines those values. The expected returned text is “Forest Notes (EPUB)”.
Answer: Ebook reuses LibraryItem's title setup, adds a format, and returns “Forest Notes (EPUB)” for the stated input.
Check: The inheritance relationship fits because an Ebook is a kind of LibraryItem. The subclass provides a suitable version of the display method.

Worked example

Make one call for different objects

A program has a Book titled “River Maps” and an Ebook titled “Forest Notes” with format “EPUB”. Both have a `display_info` method. Trace a call on each object and identify the polymorphic behaviour.
One call, two responses
Book objectEbook objectCall display_infoBook: returns titleEbook: returns title and

The caller makes the same request to both objects; their classes provide different results.

Python 3

class Book:
    def __init__(self, title):
        self.title = title

    def display_info(self):
        return self.title

class Ebook(Book):
    def __init__(self, title, file_format):
        super().__init__(title)
        self.file_format = file_format

    def display_info(self):
        return self.title + " (" + self.file_format + ")"

items = [Book("River Maps"), Ebook("Forest Notes", "EPUB")]
for item in items:
    print(item.display_info())
  1. State preconditions and input
    The input is a list containing a Book and an Ebook. Each object has a `display_info` method. The Book method returns its title; the Ebook method returns its title with its format, as defined in the code.
  2. Trace each call
    The loop first calls `display_info` on the Book, which returns “River Maps”. It next calls the same method name on the Ebook, whose overridden method returns “Forest Notes (EPUB)”. The expected output is those two lines in that order. Polymorphism is shown because the same method call leads to results suited to the two object types.
Answer: Expected output: `River Maps`, followed by `Forest Notes (EPUB)`. The call is shared, while the response depends on the object's class.
Check: To trace a call, identify the current object and use the method implementation provided by its class.

Common mistakes and how to avoid them

Assuming an underscore-prefixed Python attribute is completely inaccessible.
Correction: A leading underscore is a convention signalling intended internal use. Use the class's methods as the intended way to manage the data.
Checking only changes to an attribute and assuming the initial value must therefore be suitable.
Correction: Consider both object creation and later changes. The constructor should establish suitable starting data, and methods should check changes when needed.
Assuming Python's `isinstance(value, int)` excludes Boolean values.
Correction: In Python, Boolean values are related to integers. If a rule requires an integer but excludes `True` and `False`, check `type(value) is int` as in the example.
Using inheritance only because two classes share some code.
Correction: Check for a meaningful kind-of relationship. In this lesson, an Ebook is a kind of LibraryItem.
Calling any method call polymorphism, even when objects do not share the method name.
Correction: Look for a shared method call that produces behaviour suited to different object types.

Lesson summary

  • Encapsulation keeps related data and its managing methods together and lets a class control starting values and changes.
  • Inheritance lets a more specific subclass reuse or adapt a more general class.
  • Polymorphism lets different object types respond differently to the same method call.
  • For a trace, identify the object, its class, the method implementation, and the expected result.

Check your understanding

Question 1

A method accepts a new page count only if it is a positive integer and not a Boolean value. Which idea is most directly shown?
  1. Encapsulation, because the class controls changes to its data
  2. Inheritance, because the value is stored in an object
  3. Polymorphism, because the method has an input
  4. Inheritance, because invalid input is rejected
Show answer and explanation
Encapsulation, because the class controls changes to its data
The class method controls how the object's data changes, which illustrates encapsulation.

Question 2

AudioBook is based on LibraryItem and adds a narrator attribute. Which class inherits from the other?
  1. LibraryItem inherits from AudioBook
  2. AudioBook inherits from LibraryItem
  3. AudioBook and LibraryItem are the same object
  4. The narrator attribute alone makes AudioBook polymorphic
Show answer and explanation
AudioBook inherits from LibraryItem
AudioBook is the more specific class, so it is the subclass based on LibraryItem.

Question 3

A program calls `display_info` on a Book and an Ebook. The Book returns its title; the Ebook returns its title and format. Which idea is demonstrated?
  1. Encapsulation only
  2. Inheritance only
  3. Polymorphism
  4. Changing the parent object's type
Show answer and explanation
Polymorphism
The same method call produces behaviour suited to each object's class.

Key terms

Class
A description used to create objects with related data and methods.
Object
A particular instance of a class.
Encapsulation
Keeping related data and the methods that manage it together, with controlled ways to use or change the data.
Inheritance
A relationship in which a more specific class is based on a more general class.
Subclass
A class based on another class that can reuse, add, or adapt behaviour.
Override
Define a subclass method with the same name as a parent method to provide subclass-specific behaviour.
Polymorphism
The ability for different object types to respond to the same method call with behaviour suited to each type.

Continue through ICS4U

View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons

Tutor support for A2.2 · Apply encapsulation, inheritance and polymorphism

Working on A2.2 · Apply encapsulation, inheritance and polymorphism in ICS4U? Bring the question and your own attempt. In a live session, you can trace a small example and find the first step where the output differs from what you expected. Ask about the first step that does not make sense, then try a similar question yourself.

Explore coding tutoring · Request an eligible free 30-minute introduction. Your request is matched by subject and language; a tutor must accept before a time is confirmed.

برای مبحث A2.2 · کاربرد کپسوله‌سازی، وراثت و چندریختی در درس ICS4U، سؤال و تلاش خود را همراه بیاورید. در جلسه می‌توانید یک مثال کوچک را دنبال کنید و نخستین گامی را که خروجی با انتظار شما فرق دارد پیدا کنید. راهنمای معلم برنامه‌نویسی را ببینید یا جلسهٔ معارفهٔ رایگان ۳۰ دقیقه‌ای درخواست کنید. زمان جلسه پس از پذیرش معلم قطعی می‌شود.

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation A2.2. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question