Java接口默认方法中能否调用自身方法实现递增逻辑?
Can I Implement a Default Method in
GroupIdentifier That Returns a New Instance with Incremented Revision? Absolutely! This is totally doable with Java's default interface methods and an anonymous inner class. Let's walk through the exact implementation:
The Updated Interface
public interface GroupIdentifier { Integer getRevision(); // Default method to return a new GroupIdentifier with incremented revision default GroupIdentifier getNextRevisionIdentifier() { return new GroupIdentifier() { @Override public Integer getRevision() { // Call the original getRevision() and add 1 return GroupIdentifier.this.getRevision() + 1; } }; } }
How It Works
- The
getNextRevisionIdentifieris a default method (introduced in Java 8), which lets us add concrete implementation logic directly to the interface without breaking existing implementations. - Inside the default method, we create an anonymous inner class that implements
GroupIdentifier. ItsgetRevisionmethod calls the original interface'sgetRevision()(viaGroupIdentifier.this.getRevision()) and returns the value incremented by 1.
Example Usage
Here's how you'd use this with a concrete implementation of GroupIdentifier:
public class ConcreteGroup implements GroupIdentifier { private Integer revision; public ConcreteGroup(Integer revision) { this.revision = revision; } @Override public Integer getRevision() { return revision; } public static void main(String[] args) { ConcreteGroup group = new ConcreteGroup(5); System.out.println("Original revision: " + group.getRevision()); // Output: 5 GroupIdentifier nextGroup = group.getNextRevisionIdentifier(); System.out.println("Next revision: " + nextGroup.getRevision()); // Output: 6 } }
Key Notes
- This works because the default method can access the interface's abstract methods (like
getRevision()) as long as the implementing class provides a concrete implementation for them. - The anonymous inner class is tied to the original instance's context, so it correctly uses the current revision value to compute the next one.
内容的提问来源于stack exchange,提问作者Chamly Idunil
相关产品推荐
相关产品推荐

