Friend概念在Java中的实现 [英] Implementation of Friend concept in Java

查看:154
本文介绍了Friend概念在Java中的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用Java(如C ++)实现朋友概念?

How does one implement the friend concept in Java (like C++)?

推荐答案

Java没有C ++中的friend关键字.但是,有一种方法可以模拟这种情况.实际上可以提供更精确控制的方法.假设您具有类A和B.B需要访问A中的某些私有方法或字段.

Java does not have the friend keyword from C++. There is, however, a way to emulate that; a way that actually gives a lot more precise control. Suppose that you have classes A and B. B needs access to some private method or field in A.

public class A {
    private int privateInt = 31415;

    public class SomePrivateMethods {
        public int getSomethingPrivate() { return privateInt;  }
        private SomePrivateMethods() { } // no public constructor
    }

    public void giveKeyTo(B other) {
        other.receiveKey(new SomePrivateMethods());
    }
}

public class B {
    private A.SomePrivateMethods key;

    public void receiveKey(A.SomePrivateMethods key) {
        this.key = key;
    }

    public void usageExample() {
        A anA = new A();

        // int foo = anA.privateInt; // doesn't work, not accessible

        anA.giveKeyTo(this);
        int fii = key.getSomethingPrivate();
        System.out.println(fii);
    }
}

usageExample()显示了它是如何工作的. B的实例无权访问A的实例的私有字段或方法.但是,通过调用GiveKeyTo(),类B可以获得访问权限.没有其他类可以访问该方法,因为它需要一个有效的B作为参数.构造函数是私有的.

The usageExample() shows how this works. The instance of B doesn't have access to the private fields or methods of an instance of A. But by calling the giveKeyTo(), class B can get access. No other class can get access to that method, since it a requires a valid B as an argument. The constructor is private.

然后,类B可以使用密钥中传递给它的任何方法.尽管设置起来比C ++老友记关键字要笨拙,但要细得多.类A可以选择要公开给哪些类的方法.

The class B can then use any of the methods that are handed to it in the key. This, while clumsier to set up than the C++ friend keyword, is much more fine-grained. The class A can chose exactly which methods to expose to exactly which classes.

现在,在上述情况下,A授予对B的所有实例和B的子类实例的访问权限.如果不需要后者,则GiveKeyTo()方法可以使用getClass()在内部检查其他类型的确切类型. ,如果不是正好是B,则抛出异常.

Now, in the above case A is granting access to all instances of B and instances of subclasses of B. If the latter is not desired, then the giveKeyTo() method can internally check the exact type of other with getClass(), and throw an exception if it is not precisely B.

这篇关于Friend概念在Java中的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆