我怎样才能同时提供两个接口("公共"和"扩展"接口)?

Mic*_*ann 1 java oop

我有块使用函数执行计算step().这些块可以相互连接connect(Block).

interface Block {
    void connect(Block b);
    void step();
}
Run Code Online (Sandbox Code Playgroud)

但是,从具体的块实现(例如step)中,应该可以read从连接的块中:

class ABlockImpl implements Block {
    private Block src; // link to the block this block is connected to
    public void connect(Block b) {
        src = b;
    }

    public void step() {
        double x = src.read(); // XXX src is of type Block and there is no read() in Block
        /* ... */
    }

    public double read() {
        return 3.14;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于没有read()Block,这将不会编译.对于客户来说,"公共"Block接口就足够了,我read只需要在内部.我可以添加read到Block界面,但对我来说这感觉不对.

由于有座的多种不同的实现,我不能投srcABlockImpl调用之前read.

还有另一种"隐藏"的方法read吗?

Pet*_*rey 6

您可以拥有公共接口和本地包

public interface MyPublicInterface {

}

interface MyDirectInterface extends MyPublicInterface {

}

class MyImpl implements MyDirectInterface {

    public void add(MyPublicInterface mpi) {
         MyDirectInterface mdi = (MyDirectInterface) mpi;
         // use mdi
    }

}
Run Code Online (Sandbox Code Playgroud)