Don't say, “reference type.” A reference type means a type from which objects are (at least in theory) created, meaning arrays, classes, and interfaces. The opposite of reference type is, “primitive type," and there are eight kinds of primitive type. You doubtless meant to say, “declared type.”
Please don't write comments such as to produce
long lines, because they are so difficult to read.Write
/* comments */ instead, and spread them over multiple lines.
Please avoid single‑letter names for parameters or variables as much as possible; use names that make their meaning obvious.
What does the book say about the problem? Which book is it? Is it Boyarsky and Selikoff? I don't have a copy. Where did the code you showed come from? It shows some poor design. I presume that poor design is there to show a point.
As far as I am concerned, polymorphism and overriding apply to instance methods, instance methods, instance methods, and instance methods. Nothing else. It doesn't even apply to
private instance methods because they cannot be overridden.
If an instance method is called at runtime on the name of an object, the bytecode says to look for the method declaration in the
Class<?> object that the object was derived from. That is the
Cass object corresponding to the runtime type of the object.
So, calling an instance method might take you to the
Class<Cat> object or to the
Class<Dog> object. There you might find a method definition, and that definition will be used. You might get, “Woof‑Woof” or, “Miaow.” That is called late binding, andd is also called dynamic binding and also called runtime binding.
Which version of a
static method is called is determined at compile‑time. The compiler sees that the declared type is Animal and calls any
static methods on that type, Animal. That is called early binding or static binding or compile‑time binding. The details of a
static method are determined by static binding. All fields also undergo compile‑time binding. If you have fields with the same name in superclass and subclass, they do not override each other, but hide each other. They are two fields completely independent of each other, and therefore a potent source of confusion. The same applies to
static methods; even if they have the same name, they are independent of each other and can only be hidden not overridden. No, the name field does not bind to any object, but to the declared type of the variable. That is why
static members should always be referred to by
ClassName.memberName and never by
ObjectReferenceName.memberName.
The overridden method in
Child calls the fields linked at compile‑time to its declared type, which for
t is
Person. Yes, that is very confusing code.