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

Java类如何不引入额外import 根据状态切换两个interface的访问权限

实现思路

核心通过状态标记+接口类型隔离实现访问控制,全程不需要引入额外依赖:

  • 给Cube类新增isFixed布尔状态位,默认值为false,标识是否已完成固定
  • 实现properties接口方法时先校验状态:已固定时调用修改类方法直接抛出运行时异常
  • 实现calculate接口方法时先校验状态:未固定时调用计算类方法直接抛出运行时异常
  • 调用fixed()方法后返回的实例用calculate类型接收,编译层面直接限制只能访问计算接口的方法

完整实现代码

public interface properties <T> {
    T size(int length);
    T fixed();
}

public interface calculate{
    int volume();
    int area();
}

public class Cube implements properties<Cube>, calculate{
    private int length;
    private boolean isFixed = false;

    public Cube(int length){this.length = length;}

    @Override
    public Cube size(int length) {
        if (isFixed) {
            throw new IllegalStateException("Cube已固定,无法修改长度");
        }
        this.length = length;
        return this;
    }

    @Override
    public Cube fixed() {
        this.isFixed = true;
        return this;
    }

    @Override
    public int volume() {
        if (!isFixed) {
            throw new IllegalStateException("Cube未固定,无法计算体积");
        }
        return length * length * length;
    }

    @Override
    public int area() {
        if (!isFixed) {
            throw new IllegalStateException("Cube未固定,无法计算表面积");
        }
        return 6 * length * length;
    }
}

使用示例

// 未固定阶段,用properties接口接收,仅能访问修改方法
properties<Cube> cube = new Cube(2);
cube.size(3).size(5); // 链式修改长度正常

// 调用fixed后用calculate接口接收,仅能访问计算方法
calculate fixedCube = cube.fixed();
System.out.println(fixedCube.volume()); // 输出125
System.out.println(fixedCube.area()); // 输出150

// 以下调用都会触发异常:
// cube.size(10); // 运行时异常:已固定无法修改
// fixedCube.size(4); // 编译期报错:calculate接口无size方法
// new Cube(3).volume(); // 运行时异常:未固定无法计算

内容的提问来源于stack exchange,提问作者Heartless

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:36:05