Checkpoint 7.6.1. Interface Implementation.
Consider a program that follows these steps:
-
An interface
Drawableis defined with a single methoddraw(). -
Two classes,
CircleandRectangle, implement theDrawableinterface and provide their own definitions of the draw() method. -
A method
drawShape(Drawable shape)is created in a separate class. This method takes a Drawable object as a parameter and calls itsdraw()method, demonstrating polymorphism. -
In a main method, instances of
CircleandRectangleare created and passed to drawShape(), demonstrating polymorphism.
Which of the following statements is true regarding this implementation?
- The
Drawableinterface must provide an implementation for thedraw()method. - No. Interfaces in Java only define method signatures without providing implementations (except for default and static methods, which are not used here). The actual implementation of
draw()must be provided by classes that implement the interface. - The
CircleandRectangleclasses must override thedraw()method from theDrawableinterface. - Correct! The
CircleandRectangleclasses must override thedraw()method from theDrawableinterface. - The
drawShape(Drawable shape)method must be defined inside theDrawableinterface. - No! Interfaces are meant to define behavior but not necessarily contain utility methods like
drawShape(). This method is better suited for a separate class where it can accept anyDrawableobject and invoke itsdraw()method. - We cannot pass a
CircleorRectangleobject todrawShape()because they are not of type Drawable. - Since
CircleandRectangleimplementDrawable, they are considered polymorphic types ofDrawable. This allows them to be passed as arguments todrawShape(Drawable shape), which expects aDrawableparameter.
