Shiba
or any other classes, so we can just look at the Dog.Shiba
overrides Dog
so all Shibas
will use C instead of A.Dog
is incompatible with Shiba
? Parent p = new Child()
works fine. This is really useful for things like Interfaces and generic Collections because we might only care about using generic methods, and not the specific implementation that users chose to provide.Child c = new Parent()
will error because the child might have new methods that don't exist in the parent.rarePupper
's dynamic type is Shiba
but its static type is Dog
so Shiba.playWith(Dog)
is chosen as the method.Shiba
?
When the compiler chooses a method, it always starts at the static method. Then, it keeps going down the inheritance tree until it hits the dynamic method. Since F has a different signature than D, it isn't an overriding method and thus the compiler won't see it. But E is (since it has the same signature as D), so that is why it is chosen instead.Dog s = new Shiba()
has type Dog
on the left and Shiba
on the right.Dog
is the static type of s
: it's what the compiler believes the type should be when the program is compiled. Since the program hasn't run yet, Java doesn't know what exactly it is- it just knows it has to be some type of Dog
.Shiba
is the dynamic type: it gets assigned during runtime.cute doggo
gets printed because getType()
is a static method! Therefore, Java looks at the static type of d
, which is Dog
.
(If getType()
weren't static, then shiba inu
would have been printed as usual.)cute doggo
also gets printed!! This is because static methods cannot be overridden. When toString()
is called in Dog
, it doesn't choose Shiba
's getType()
because getType()
is static and the static type is Dog
.shiba inu
gets printed. This is because casting temporarily changes the static type: since the static type of d
is Shiba
in line 2, it chooses the getType()
from Shiba
.