Why the output of the following program runs finalize of Classmate before finalize() of Course ? Classmate uses the class Course object so its finalize() should run after the finalize() of Course ? But the output shows the reverse.WHY?
class Classmate{
Course mca;
Classmate(){
System.out.println("Student const. `enter code here`called");
mca = new Course();
mca.getCourse();
}
@Override
protected void finalize() {System.out.println("good bye Student");
}
}
class Course{
Course(){
System.out.println("Course const. called");
}
void getCourse(){
System.out.println("your ccourse is MCA");
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
System.out.println("goodbye course");
}
}
public class Composition {
public static void main(String[] args) {
Classmate ram = new Classmate();
ram=null;
System.gc();
for(int i=0;i<5;i++)
System.out.println("i is "+i);
}
}
OUTPUT:
Student const. called
Course const. called
your ccourse is MCA
good bye Student
i is 0
goodbye course
i is 1
i is 2
i is 3
i is 4