lunes 2 de mayo de 2011

90% of programmers dont know that this==super!

In programming lenguages the use of super is commonly mistaken. Usually super seems to call the method of the super class of the class where the method is implemented.
Factoid :  super  mean start the search in the superclass of the receiver.

The error is easy to induce, a lot of programmers learns by induction the use of super (or learning by example).
This causes a misconception of the real definition of super and self (or this in java).
The real use of self or super is to specify how to search the message (or method) in the class hierarchy, I don't think a common programmer will think this way (not in the way algorithm is implemented).

Lets see the example :
example3 and example4 are instances of Three and Four respectively.

if you send the message result2 to example3 it will return 2
if you send the message result2 to example4 it will return 4

Also


if you send the message result3 to example3 it will return 2
if you send the message result3 to example4 it will return 2

But what will happened if Three implements the test message  test as { return 3 } when you send the result3 message to example4?

It will return 3 or 2? Actually it will return 2. If you don't know why check the definition of self and super




self (or this) means : start the search in the receiver class (receiver here is the object which get the message)

Super really means  : start the search in the superclass of the class containing the method in which super was used.

So the answer of the question it will return 2 or 3 depends on where the super sends is implemented (in which class!) not as self!
Google Analytics Alternative