Supposing I have a class that holds a reference to an InputStream that is reading from a file, or an OutputStream that is writing to a file (or another example, if you're an Android developer, a MediaPlayer instance).
Knowing that Java passes objects by value, what happens when you have something like the following pseudocode?
class MyClass {
InputStream is;
public void read() {
// initialize inputstream here (assume it's reading from a file that contains the alphabet from A-z)
is.read();
}
public MyClass() {
this.read();
}
}
class OtherClass {
MyClass mine = new MyClass();
public OtherClass() {
mine.read();
LastClass lastClass = new LastClass(mine);
}
}
class LastClass {
MyClass his;
public LastClass(MyClass mc) {
his = mc;
his.read();
}
}
My question is, since we're passing objects by value, how are they able to maintain a reference to the open resource? Also, just to be clear, by the time everything is executed, how many instances of MyClass exist?
While it is true that Java is pass-by-value, you must keep in mind that for objects, it is the value of the object's reference that is passed.
Although there may not seem to be a difference between pass-by-reference and passing the value of a reference, their are subtle distinctions. See is-java-pass-by-reference for a more in-dept discussion on the subject.
So to answer your question, in your example you will have one instance of MyClass
created for each instance of OtherClass
you create.
As for the input stream, since it is initialized in MyClass.read()
rather than in the MyClass
constructor, then we can assume that the file will be opened each time read()
is called and one byte will be read from the file. The InputStream
will stay opened but the next time read()
is called then a reference to a new InputStream
will be assigned to the is
member variable and the old one would be release for garbage collection. It is hard to say more that that without more code.
When you create an OtherClass
object, the following happen:
MyClass
object is created in the heap and a reference to this object is stored in the mine
member variable.
MyClass
constructor calls the read()
method. So a new InputStream
is initialize and the first byte is read from the file. OtherClass
constructor calls mine.read()
. So a new InputStream
is initialize and the first byte is read from the file. LastClass
object is created. The value of the reference to the MyClass
object stored in variable mine
is passed to the constructor.
MyClass
reference is saved in the his
member variable of the new LastClass
object. LastClass
constructor calls mine.read()
. So a new InputStream
is initialize and the first byte is read from the file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.