Reputation: 1872
This may be silly question. but i want to know there is some possibility to do this.
Suppose I have interface like
public interface GroupIdentifier {
Integer getRevision();
}
And I need another method named as getNextRevision. So what i can do is, implement default method inside same interface and return next number.
EX :
public interface GroupIdentifier {
//OUTER GET REVISION
Integer getRevision();
default GroupIdentifier getNextRevisionIdentifier() {
return new GroupIdentifier() {
//INNER GET REVISION
public Integer getRevision() {
//Here I want to return OUTER GET REVISION + 1
return null;
}
};
}
}
Is there some possibility to this.
Upvotes: 3
Views: 1598
Reputation: 200168
I believe what you wanted to write is this:
public interface GroupIdentifier {
Integer getRevision();
default GroupIdentifier getNextRevisionIdentifier() {
return new GroupIdentifier() {
public Integer getRevision() {
return GroupIdentifier.this.getRevision() + 1;
}
};
}
}
You just didn't find a way to refer to the enclosing instance's getRevision()
. BTW if your interface is as you've posted it, with just a single abstract method, then you can implement it much more cleanly:
public interface GroupIdentifier {
Integer getRevision();
default GroupIdentifier getNextRevisionIdentifier() {
return () -> getRevision() + 1;
}
}
Upvotes: 2
Reputation: 1872
I have fixed my solution as below.
public interface GroupIdentifier {
Integer getRevision();
default GroupIdentifier getNextRevisionIdentifier(GroupIdentifier identifier) {
return new GroupIdentifier() {
@Override
public Integer getRevision() {
return identifier.getRevision() + 1;
}
};
}
}
Upvotes: 1
Reputation: 393831
I'm not sure what's the purpose of getNextRevisionIdentifier()
returning an instance of GroupIdentifier
.
If you want getNextRevisionIdentifier()
to return the next identifier, let it return an Integer
:
public interface GroupIdentifier {
Integer getRevision();
default Integer getNextRevisionIdentifier() {
return getRevision () + 1;
}
}
Upvotes: 6
Reputation: 57124
Return a new instance of GroupIdentifier
for which you implement getRevision
accordingly:
public interface GroupIdentifier {
//OUTER GET REVISION
Integer getRevision();
default GroupIdentifier getNextRevisionIdentifier() {
//INNER GET REVISION
Integer outer = getRevision();
return new GroupIdentifier() {
@Override
public Integer getRevision() {
return outer + 1;
}
}; // can be simplified to return () -> outer + 1;
}
}
This can be run, e.g. via
public static void main(String[] args) {
GroupIdentifier groupIdentifier = new GroupIdentifier() {
@Override
public Integer getRevision() {
return 1;
}
};
System.out.println(groupIdentifier.getNextRevisionIdentifier().getRevision());
}
outputting
2
Upvotes: 2