Accessing an instance of a variable from another class in Java

扶醉桌前 提交于 2019-11-30 06:05:04

问题


Is it possible to access an instance of a variable in one class from another class in Java.

Let's say you have the following in Class A:

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

I want to make changes to the queue in this class and then be able to use to access it from another class.

How would i access the instance of buffer from another class? Is it even possible?


回答1:


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();



回答2:


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(); }

}



回答3:


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();


来源:https://stackoverflow.com/questions/8689553/accessing-an-instance-of-a-variable-from-another-class-in-java

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