Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
I am trying to understand the method hiding concept. In below code why is the methodCall() in the ChildClass not getting called? As the Method() is inherited from the ParentClass, it should be able to access the methodCall() in the ChildClass right?
Paweł Baczyński wrote:It is because ChildClass#methodCall is static
and ParentClass#Method actually calls this.methodCall().
No, it calls ParentClass.methodCall(), not this.methodCall(). If it called this.methodCall() the output would be Child Method call, not Parent Method call.
The reason why it calls ParentClass.methodCall() is because you can't override static methods, you can only shadow them. Any call made to static methods uses the declared type (so in this case the enclosing class ParentClass), not the actual type as is the case for instance methods.
Again, your perspective that a Parent class somehow "accesses" methods of a subclass is misleading and clouding your understanding of what's happening.
What's really happening is the result of what's called early binding (also known as static binding). The method in question is declared as a static method therefore it does not participate in polymorphism which is achieved via late binding (aka dynamic binding) which happens at run time. Calls to static methods are resolved at compile time. In this case, since the call to the static method occurs in the superclass and is not qualified by a reference of some type, the compiler will statically bind the call to the method in the superclass. If you add a direct call to the static methodCall() in the ChildClass.main() method, say after line 22, you'll see the output of line 16.