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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With