Accessing an instance of a variable from another class in Java

随声附和 提交于 2019-11-28 14:29:30

Add a getter:

public class Whatever {

    private BlockingQueue<byte[]> buffer = new LinkedBlockingQueue<byte[]>();

    public BlockingQueue<byte[]> getBuffer() {
        return buffer;
    }
}

Then if you have an instance of Whatever:

Whatever w = new Whatever();
BlockingQueue<byte[]> buffer = w.getBuffer();

Change the private to public. Then you can access the variable buffer like this:

A myobj = new A();
BlockingQueue<byte[]> bq = myobj.buffer;

For more details, consult this article on access control: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

An arguably better way of doing this is using getters. That is, create a get() method in class A which simply returns buffer.

public BlockingQueue<byte[]> getBuffer() {
    return buffer
}

Then you can access it by calling getBuffer():

BlockingQueue<byte[]> bq = myobj.getBuffer();

Its usually best to encapsulate collections and not expose the collections itself. Instead you should expose the operations you want to perform

public class Whatever {

    private final BlockingQueue<byte[]> buffer = new LinkedBlockingQueue<byte[]>();

    public void enque(byte[] bytes) { buffer.add(bytes); }

    public byte[] takeNext() { return buffer.take(); }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!