Polymorphism
Introduction: 9.6.0
Polymorphism
means “many forms”- In Java it means that the method that gets called at
runtime
depends on the type of object at runtime- Each subclass of a parent overrides a parent method, so the behavior of the same method depends on the type
inheritance-based polymorphism
- Each subclass of a parent overrides a parent method, so the behavior of the same method depends on the type
- In Java it means that the method that gets called at
- Variables in java have a
compile-time
type and aruntime
type- The compile-time type is the type declared, and the runtime type is the type used in declaration
Animal myPet = new Dog();
- Animal is the compile-time type
- Dog is the runtime type
- At compile-time, Java will check if the declared type has or inherits all methods and fields called on it
- If it isn’t found, we give a compiler error
- At runtime, the execution environment will look for the same method first in the runtime type, rather than the declared type
- If it isn’t found, we go up the chain of parent classes until we find it.
-
Java also checks if the object actually being set is the type of the declared variable
Object mypet = new Dog();
mypet.bark(); // Compile error! java.lang.Object has no method bark()!
Summary: 9.6.2
- At compile time, methods in the
declared type
determine the correctness of a non-static method call - At run-time, the method in the
actual object type
is executed for a non-static method call- This is called polymorphism!
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.