Quiz 5: Inheritance 1
1. Which is relevant to the concept of inheritance in object-oriented programming?
- Dynamic Binding
- Method Overriding
- Polymorphism
- All of them
Correct answer: All of them
Explanation:
- Polymorphism: a child class can "stand in" for its parent class.
- Method Overriding: child class overrides a method inherited from a parent class
- Dynamic Binding: more complicated - see the information under the dynamic binding definition in section 5.3
More information can be found in Section 5.3.
2. In the Square vs. Rectangle example discussed in class, which statement is correct?
Rectangleshould be a subclass ofSquare- There should be no inheritance relationship between
RectangleandSquare Squareshould be a subclass ofRectangle- Either
RectangleorSquareshould be a subclass of the other
Correct answer: There should be no inheritance relationship between
RectangleandSquare
Explanation:
In a mathematical sense, every square is a rectangle.
However, if a
Squarewere to inherit from aRectangle, it would inherit methods such assetWidth()andsetHeight(). TheSquarecould override these functions to provide correct functionality, but publicly exposing such an API defies the fundamental property of a square: a rectangle with equal height and width.This is fundamentally the same issue as the
Stack<E> extends Vector<E>problem.
3. Which of the following views about inheritance is based on the "is-a" relation?
- Neither type view nor module view
- Type view
- Module view
- Both type and module views
Correct answer: Type View
Explanation:
Recall the definition for subtype:
Data type \(t_2\) is a subtype of data type \(t_1\) if every value of \(t_2\) can be assigned to a variable of \(t_1\).
4. In Java, Stack is a subclass of Vector. Which of the following statements is incorrect?
- The LIFO property of
Stackcan be violated when the methods inherited fromVectorare called. Stackreflects the module view of inheritance for code reuse.Stackreflects the type view of inheritance.Stackinherits all the methods ofVector.
Correct answer:
Stackreflects the type view of inheritance.
Explanation:
The statement is incorrect because a
Stackis not aVector. The essential quality of aStackis its LIFO property, which is violated by several methods inherited fromVector.