Shibaor any other classes, so we can just look at the Dog.
Shibaswill use C instead of A.
Dogis incompatible with
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
Shibabut its static type is
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
Dogon the left and
Shibaon the right.
Dogis 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
Shibais the dynamic type: it gets assigned during runtime.
cute doggogets printed because
getType()is a static method! Therefore, Java looks at the static type of
d, which is
getType()weren't static, then
shiba inuwould have been printed as usual.)
cute doggoalso gets printed!! This is because static methods cannot be overridden. When
toString()is called in
Dog, it doesn't choose
getType()is static and the static type is
shiba inugets printed. This is because casting temporarily changes the static type: since the static type of
Shibain line 2, it chooses the