-The class must be loaded, before an object can be created from a class. First of all, the Java runtime locates the class. Then reads the class into memory. Thereafter Java looks for any static initializers that initialize static fields.
A class is loaded the first time we create an object from the class or the first time we access a static field or method of the class. For example, when we run the main method of a class, the class is initialized because the main method is static.
- An object is created from a class when we use the new keyword. To initialize the class, Java allocates memory for the object and sets up a reference to the object. So the Java runtime can keep track of it. Then, Java calls the class constructor, which is like a method but is called only once, when the object is created. The constructor is responsible for doing any processing required to initialize the object, such as initializing variables, opening files or databases, and so on.
-The object lives its life, providing access to its public methods and fields to whoever wants and needs them.
-When it's time for the object to die, the object is removed from memory and Java drops its internal reference to it. You don't have to destroy objects yourself. A special part of the Java runtime called the garbage collector takes care of destroying all objects when they are no longer in use.
Comments
Leave a comment