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

编程入门 行业动态 更新时间:2024-10-22 13:39:23
本文介绍了我可以限制另一个类可以在 Java 中调用的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 ABC 类,其中 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:关键词]

本文发布于:2023-03-28 19:03:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/737020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!