Creating and Destroying Objects in Java
All classes extend the Object class, and thus inherit
methods from that class.
- Objects are created by calling the constructor with the new
keyword.
Example: p = new Point(2, 3);
Every class has a default constructor which does nothing.
- A constructor may start by calling a constructor of the superclass:
super(2, 3); but this call must be the first statement of
the constructor.
- Objects cannot be explicitly destroyed. A garbage collector frees
the storage space of objects that are no longer referenced.
The finalize method can be used to perform some
actions when an object is being destroyed by the garbage collector.
- The Object class provides (not very functional)
methods equals(Object obj) to test shallow value equality,
hashCode() which returns a different value for every object,
clone() which returns a clone of an object,
and getClass() which returns the Class
of the object.
Most classes will override the methods equals and
clone if they wish to really support them.
Example:
public class MyFile {
private Stream File;
public MyFile(String path) {
File = new Stream(path);
}
// ...
public void close() {
if (File != null) {
File.close();
File = null;
}
}
protected void finalize() throws Throwable {
super.finalize();
close();
}
}