9.6 Polymorphism
As discussed in the previous chapter, polymorphism is the capability of a method to do different things depending on the object it is acting upon. This process allows for the declaration of objects using a superclass that can then be instantiated as a specific subclass. This enables Arrays
and methods to utilize polymorphism.
Polymorphism is also capable of calling the correct method for an object even when that object is disguised as a more generic reference type. This process is evident when looking at how object methods are called in compile time and run time.
At the time a program gets compiled, methods in or inherited by the declared type determine the correctness of a non-static method call. During the process of compiling a program, Java checks the declared type of an object to determine if all of the called methods exist:
The Java compiler will only check the Person
class to see if the getName
method exists. It will only successfully compile if it exists in the Person
class, regardless of whether or not it exists in the Student
class. This means that objects declared as a superclass type but instantiated as a subclass type can only call methods that exist in both classes.
At the time a program runs, the methods in the actual object type get executed. If the method doesn’t exist there, Java looks to the superclass for the method. From the previous example, at run time, Java will look for the getName method in the Student
class first. If it doesn’t exist, it will look in the parent class.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
In order for a program to compile, any method that an object uses …
Given the Solid
class, extend it with:
Pyramid
Cylinder
RectangularPrism
Sphere
Make sure to create the constructor and override the volume()
and surfaceArea()
methods.
Also extend RectangularPrism
with Cube
.
Note: The pyramid should be a rectangular pyramid.
HINT: You can look up formulas for how to compute the volume and surface area of a certain type of shape online.