just for learning purpose by writing in English
RECOMMENDED VIDEO WALKTHROUGH
Inheritance and Dynamic Method Selection — Content Review by Sohum Hulyalkar
What is Static Type & Dynamic Type?
Static type: what the object type shoud be?
Dynamic type: what the object type actually be?
let's see the example below:
class A {
void f(A obj) {1};
}
class B extends A {
void f(A obj) {2};
void f(B obj) {3};
}
A peach = new A();
A banana = new B();
Then both the peach and banana static type is A
the dynamic type: peach is A, banana is B
you can assume that it assign a instance to peach after using new A() to create a dynamic instance whose type is A in the runtime.
and the static type of new A() is A too!
So What's the Usage of Static Type and Dynamic Type?
I recommend watching the walkthrough video that has many commond usage examples and try to finish the discussion paper on your own.
In the Compile Time:
Does the method exists?
Java using static type:
- Check if the type is matched or not, and the function will be called exists or not
- LOCK IN on a function signature that should be executed in the runtime
In the Runtime Time:
Does there a better choices?
Java based on the dynamic type decide:
- what exact method should be used?
- while it must be the identical signature which is LOCKED IN at the compile time
Side Notes:
Suffice
While it's common that the type is not identical to the signature, then it will be sufficed if the type is a subclass of the signature parameter type.
Thus we have polymorphism
casting
Temporarily change the static type at the compile time, in order to invoke wanted method, while it DO NOT check the type is casting correctly at the compile time you can either change the variable which invoking the method call
((B) peach).f(peach);
or change the parameter type which passed in the method
peach.f((B) banana);