What is the compile time type of this? (in Java)

design-patterns, java

Solution

The type of `this` is the type of the class in which it is used. In fact, it is crucial for the visitor pattern from the article to work.

Visitor pattern implements double dispatch in two steps - selecting the appropriate `accept` method in the object being visited (first leg), and then selecting the appropriate `visit` method in the visitor (second leg). The first leg is implemented through overriding; the second leg is implemented through overloading.

Note that it is not necessary to use overloading for the second leg. In fact, it is common not to use it there for better readability. Compare these two implementations:

// Copied from Listing 29-2
public interface ModemVisitorOverload
{
    void visit(HayesModem modem);
    void visit(ZoomModem modem);
    void visit(ErnieModem modem);
}

public interface ModemVisitorNoOverload
{
    void visitHayes(HayesModem modem);
    void visitZoom(ZoomModem modem);
    void visitErnie(ErnieModem modem);
}

The second implementation is not using the overloading. It works in exactly the same way, except human readers of the code immediately see what is going on.

Problem

I suspect it is the type of the class in which it is written but I am not 100% sure, could someone please confirm my suspicion and perhaps give a reference to Java Language Specification where this behaviour is defined? Let's say class `A` has a method `a()` which uses the `this` keyword in its body, and class `B` extends class `A`. Now class `B` has inherited method `a()`, however, I am not sure if the compile time type of `this` in `B.a()` is now `A` or `B` ? I am asking this because I am trying to understand how the visitor pattern works, as it is described in this Robert C. Martin's Visitor chapter from The Principles, Patterns, and Practices of Agile Software Development. It seems to be crucial to know the compile time type of `this` if one wants to fully understand the visitor pattern because overloaded method calls are resolved at compile time. More specifically, I refer to the compile time type of `this` in the `accept` methods in the visitor pattern.

Original source