Page 227 - Computer_Science_F5
P. 227
Computer Science simpler by letting programmers This implies that a method already
concentrate on the shared behavior defined in a superclass can have a subclass
define it individually. By overriding
and interface between several
a method, the subclass can customise
objects. This concept encourages
its behavior according to its specific
improved code organization,
FOR ONLINE READING ONLY
increases modularity, and facilitates
utilise the functionality inherited from
comprehension. requirements, while still being able to
the superclass. For example, consider a
superclass called Animal with a method
(b) Relationship between inheritance called makeSound(). The Animal class
and polymorphism may have a default implementation of the
(i) Inheritance facilitates makeSound() method, such as printing
polymorphism by providing a “Animal makes a sound.” The subclass
mechanism for subclasses to Dog, which extends the Animal class,
override methods inherited from can override the makeSound() method
their superclass. to provide its own implementation, such
(ii) Polymorphism allows for as printing “Dog barks.” This allows
the appropriate method for different behaviours in different
implementation to be selected subclasses. In the context of method
based on the actual type of the overriding, polymorphism treat objects
object at runtime. of different subclasses as objects of their
(iii) Through inheritance, subclasses common superclass. This promotes high
can focus behavior inherited flexibility and reusability of the code.
from their superclass, allowing
for polymorphic behaviour By declaring a method with the same
when interacting with objects name and parameters as the method in the
of the superclass type. superclass, a subclass can provide its own
(iv) Both inheritance and implementation of the method. Using a
polymorphism promote specific OOP language, the subclass can
code reuse, flexibility, and declare that it is purposefully overriding
extensibility in object-oriented the method by using the “override”
keyword. This ensures that the compiler
systems designs when they.
will produce an error if the method is
not truly overridden. During method
(c) Method overriding behaviour in overriding, certain behaviors occur and
polymorphism known as dynamic polymorphism.
Method overriding is a type of
polymorphism where a subclass provides Dynamic polymorphism, also known
its unique implementation of a method as runtime polymorphism, is a type of
that already exists in its superclass. method overriding in which the choice
218
for Advanced Secondary Schools
Computer Science Form 5.indd 218 23/07/2024 12:33

