I signed up a few moments ago, though I\'ve been making great use of this site since I took up computer programming, which I\'ve been teaching myself and consider a little h
Yes, a new object is created every time. The reference to each myObject
is allocated in the stack.
In a nutshell: should I write code like that only if I plan to invoke that method only once?
If you want myObject
to dissapear after the method execution is completed, then yes. If for some reason, you need to keep a reference to it, then you can declare it as a class member.
class MyClass {
AnotherClass myObject;
void myMethod() {
myObject = new AnotherClass();
myObject.doStuff();
}
}
This way, it will still be created each time you call myMethod()
, but It will still exist after myMethod
completes. This can be handy, or not, depending on the situation.
Does the complier skip that like of code as it sees that the object has already been created and the variable myObject already been assigned to such object?
This wont happen when using new
. It is guaranteed that it will create a fresh instance. It can be implemented using FactoryMethods (not the compiler skipping lines of code, but preventing the creation of a new object). For example, the Integer class implements this: If you try to get an integer between -128
and 127
, it will always return the same instance (wont create a new object) when using its Factory Method valueOf
Integer five = Integer.valueOf("5");//Will always return the same instance.
Integer otherFive = Integer.valueOf("5");
assert(five==otherFive);//true
Of course, using new
wont return the same instance, but always a new one
Integer five = new Integer("5");//Will create a new object each time.
Integer otherFive = new Integer("5");
assert(five==otherFive);//false
There's really not much to say about the code you added.
However, if you take a look, you'll notice two methods. Based on its names, once seems to write, the other one seems to read. That behaviour is specific to each method, so the method that writeFile
doesn't care about objects used for reading. And the method readFile
doesn't care aboute objects used to write. So theres no sense on making a fileReader
available to the writeFile
method, and so on.
Coming back to your original question, yes, this instantiates a new object each time the method is called. Its not important. Its preferable to having to ask yourself "why does the readFile
method has access to a FileWriter
instance?