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
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 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
- 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
- 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
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())- State the rule and inputsThe 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.
- Trace the requestsThe 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`.
Worked example
Reuse a library item's shared information
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())- Separate shared and specific informationA 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.
- Trace object creation and displayThe 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)”.
Worked example
Make one call for different objects
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())- State preconditions and inputThe 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.
- Trace each callThe 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.
Common mistakes and how to avoid them
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
- Encapsulation, because the class controls changes to its data
- Inheritance, because the value is stored in an object
- Polymorphism, because the method has an input
- Inheritance, because invalid input is rejected
Show answer and explanation
Question 2
- LibraryItem inherits from AudioBook
- AudioBook inherits from LibraryItem
- AudioBook and LibraryItem are the same object
- The narrator attribute alone makes AudioBook polymorphic
Show answer and explanation
Question 3
- Encapsulation only
- Inheritance only
- Polymorphism
- Changing the parent object's type
Show answer and explanation
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.