Hi, A mock exam question: Which of the classes should have a finalize method? a. A class that creates a socket b. All classes c. Any class that extends a class having a finalize method d. Any class that creates an array of primitive values Ans : a,c IMO, finalize methods are associated with Objects. JVM would call finalize() for each object before being garbage collected. Please correct me if I am wrong. All classes by default will have finalize(), unless explicitly coded, hence I think ans (b) is also correct in addition to a,c. Can anybody clarify this? Thanks Suresh [This message has been edited by Suresh Ray (edited March 21, 2000).]
All classes do have a finalize() method already, which they inherit from Object. It doesn't do anything though, unless a class overrides the finalize() method to make it do something. So, the question is meaningless unless we interpret it as follows: Which of the classes should override the finalize method? a. A class that creates a socket b. All classes c. Any class that extends a class which overrides finalize() d. Any class that creates an array of primitive values A is still reasonable - the socket should be closed. But why C? If the superclass has a finalize method that actually does something, great - that means that the subclass will inherit the same method, and whatever task needed to be done by the superclass, will still get done by the subclass. Why would we need to override it again? Only if there is some new behavior of the subclass which may require "cleanup" - like the creation of a socket. But that certainly does not apply to every class which extends a class which overrides their finalize() method. So, the answer should be A only, I think. What mock exam is this from, anyway? Post the source (and question number if you have it) and we can put this in the Mock Exam Errata forum. Thanks.
What is exactly meant by "should have" is not very clear to me. I am not sure if anybody has tried to challenge a) and c) along with the rest of the answers. Why should there be a finalize method in a class that creates a socket? What happens if I dont define the finalize() method in the subclass that extends the class that defines the finalize() method. Shouldn't the finalize() method be inherited from the superclass? The finalize() method is defined in the Object class but doesn't perform any action hence only classes that needs to perform any action before garbage collection need define this. Can anyone interprete this question properly?