Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the static type of `this` in Java 8 default interfaces?

Tags:

java

java-8

I'm implementing the visitor pattern for a project and realized I may be able to save some typing by having the default implementation of accept be the following.

public interface Visitable {
    default public void accept(Visitor v) {
        v.visit(this);
    }
}

However if the static type of this resolves to Visitable this implementation will not work so what is the static type of this in this situation?

like image 653
en4bz Avatar asked Sep 16 '15 19:09

en4bz


1 Answers

Since, in your context, this is used as a parameter type, the call will be resolved to Visitor#visit(Visitable) at compile- and runtime. Thus, you gain nothing from trying to make a default method in this scenario.

The only time this can be used polymorphically is when using it as the receiver:

public interface Foo
{
    public default void bar()
    {
         this.bar(1);
    }

    public void bar(int i);
}
like image 146
Clashsoft Avatar answered Sep 23 '22 11:09

Clashsoft