本文介绍了我可以限制另一个类可以在 Java 中调用的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 A
、B
和 C
类,其中 C
类具有可读和可写属性:
Let's assume I have classes A
, B
, and C
where class C
has readable and writable properties:
public class C {
private int i = 0;
// Writable.
public void increment() { i++; }
// Readable.
public int getScore() { return i; }
}
是否可以只让 A
使用 increment()
方法而只让 B
使用 getScore()
方法?
Is it possible to only let A
use the increment()
method and only let B
use the getScore()
method?
推荐答案
不,不能为每个班级分配访问权限.
考虑将您的类分成单独的接口,以便每个类只获取一个带有它需要的接口的对象.例如:
No, it is not possible to assign per-class access.
Consider separating your class into separate interfaces so that each class only gets an object with the interface it needs. For example:
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) { /* ... */ }
}
当然,存在安全隐患,但这应该能让您朝着正确的方向思考.
Of course, there are security implications but this should get you thinking in the right direction.
这篇关于我可以限制另一个类可以在 Java 中调用的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论