TL;TD In Java 8, is there a way for an interface default method to access instance variables?
For instance:
public interface Foo{
default getBazModified(){
return baz * 2;
}
}
public class Bar implements Foo {
int baz;
...
}
I know that sounds like travisty but is there a way to do anything like that in Java 8?
Or is the only way is to have an abstract class that implements Foo, which would have both the instance variable baz declared and have a default implementation of getBazModified()?
An interface doesn't "see" its implementation's instance fields. This is not specific to interfaces, any super-type wouldn't know about its sub-types' specific fields (or any member type for that matter).
Your solution in this case is to declare an abstract getter method in the interface and use it to read the property of the subclass:
public interface Foo{
default int getBazModified(){
return this.getBaz() * 2;
}
int getBaz();
}
And let the concrete class implement the getter:
public class Bar implements Foo {
int baz;
public int getBaz() {return this.baz;}
}
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