You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 getNextRevisionIdentifier is 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. Its getRevision method calls the original interface's getRevision() (via GroupIdentifier.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:00:05