A software team is reviewing its guidelines for reusing classes in an object-oriented program. Select every statement about composition and inheritance that is true.
A class should inherit from another class whenever it needs to reuse at least one of that class's methods.
Composition lets an object change its behaviour at run time by assigning a different component object to one of its fields.
Composition rules out code reuse, because the containing class must copy the code of every component method it offers.
If a subclass overrides a method that the superclass calls from its other methods, the superclass's own behaviour can change.
A well-designed subclass object can be passed to any code written for its superclass and still behave correctly.
Unlock full course notes by signing up
Class counts for independent variations
A team compares two designs for software whose objects vary along independent dimensions. In the inheritance design, every combination of options gets its own concrete leaf subclass. In the composition design, the main class holds one component object per dimension, and every option is one concrete component class. For each system in the table, enter the number of concrete leaf subclasses the inheritance design needs and the number of concrete component classes the composition design needs. Do not count the main class or any abstract base classes, and enter whole numbers.
Tracing a vehicle built from parts and subclasses
The Python classes below combine inheritance and composition. A Vehicle holds an engine object and delegates part of its speed calculation to it.
Give the value shown by each of the four print calls as a whole number.
Tracing a counting subclass
A programmer extends a simple collection class so that it counts how many items have been added:
What value does the program print? Give your answer as a whole number.
Construction order of a subclass with composed parts
In the Java program below, SmartPhone inherits from Phone, which inherits from Device, and each phone class also creates a part object in a field initialiser.
The statement new SmartPhone(); runs once. Arrange the five printed lines in the order they appear on the console, first line first.