我可以限制另一个类可以在Java中调用的方法吗?

sda*_*das 19 java interface

假设我有类A,B并且CC具有可读写属性:

public class C {
    private int i = 0;

    // Writable.
    public void increment() { i++; }

    // Readable.
    public int getScore() { return i; }
}
Run Code Online (Sandbox Code Playgroud)

是否可以只A使用该increment()方法并且只允许B使用该getScore()方法?

mae*_*ics 29

不,不可能分配每类访问权限.

考虑将您的类分成单独的接口,以便每个类只获得一个具有所需接口的对象.例如:

interface Incrementable { public void increment(); }
interface HasScore { public int getScore(); }
class C implements Incrementable, HasScore { /* ... */ }

class A {
  public A(Incrementable incr) { /* ... */ }
}

class B {
  public B(HasScore hs) { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)

当然,有安全隐患,但这应该让你思考正确的方向.


Jim*_*son 6

是的,但你必须经历一些旋转.

public interface Incrementable {
    public void increment();
}

public interface Readable {
    public int getScore();
}

public class C implements Incrementable, Readable
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,当您在A中定义接收对B实例的引用的方法时,请定义该方法Incrementable.对于B,定义它采取Readable.