问题
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