As exercise I wrote program which should clean object from memory by using garbage collector and method finalize()
class Dog {
boolean dogAlive = false;
String dogName;
Dog(String dogName) {
this.dogName = dogName;
}
void makeDogAlive() {
dogAlive = true;
}
void makeDogDead() {
dogAlive = false;
}
protected void finalize() {
System.out.println("test");
if (dogAlive)
System.out.println("Error: you need to finish life of your dog");
}
}
public class FinalisationExc1 {
public static void main(String[] args) {
Dog dog1 = new Dog("Azor");
dog1.makeDogAlive();
System.out.println("Your dog name is " + dog1.dogName);
System.gc();
}
}
but it looks like System.gc()
is not calling my finalize()
method? I've done all same as in example from book (I mean a methode used there but code is mine) and when example from book is working, mine not :(. Can you give me any clue where I made mistake?
EDIT:
Ok, I work a bit on my program and it looks like System.gc()
is called when I create object (do I?) by new Dog("Azor")
(1st method) instead of `Dog dog1 = new Dog("Azor")(2nd method). I'm just started to learn Java and to be when I see difference (in 2nd method we create object dog1, but do we create anything in 1st method?) I don't understand it.