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 hobby of mine.
I did look up for similar questions, but in fact I couldn't find the answer I was seeking for. Now, being aware that, in Java (that's the language I was suggested to start off with), it is considered good programming practise to declare and instantiate variables as you need them, please consider the following lines:
class MyClass {
void myMethod() {
AnotherClass myObject = new AnotherClass();
myObject.doStuff();
}
}
Now, suppose I invoke myMethod(), say, 10 times while running my program, how does that work? Is a new object create every time? Is the myObject variable reallocated every time? 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? In a nutshell: should I write code like that only if I plan to invoke that method only once? I know... shame on me for asking such a stupid question, but please give me a chance! Thanks in advance!
--------------------------- edited -----------------------------
So now am I supposed to edit this post after I get new answers?
btw... gosh that was quick, thanks a lot! And wow that confused me, a lot, I guess that's due to the fact that I've been teaching myself so...
Anyways, isn't it useless to create a new AnotherClass
Object for the myObject
variable every time? I mean, if i want to use the myObject variable throughout my program, shouldn't I declare it Once And For All? maybe in another method, that I'm going to invoke only once? Because as far as I understand, every time i invoke myMethod()
a new object is creating, thus overriding myObject's own properties aka variables or am I just talking nonsense?
--------------------------- edited -----------------------------
My doubts came after reading this code from some website I can't remember right now:
public class DataBase {
private static String buf, retString = "\n";
private static File file = new File("test.txt");
public static void readText(JTextArea area) {
try {
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);
while ((buf = br.readLine()) != null) {
area.append(buf);
area.append(retString);
}
br.close();
fr.close();
}
catch (IOException e) {
System.out.println("Exception: " + e);
}
}
public static void writeText(JTextArea area) {
try {
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(area.getText());
bw.close();
fw.close();
}
catch (IOException e) {
System.out.println("Exception: " + e);
}
}
}
I mean, why not declare FileWriter, FileReader, BufferedReader and BufferedWriter at the top of the class as they did for the other variables? and why not initialise them as well maybe in the constructor? Why doing it every time the method is called rather than using maybe the same instance variable?