A Java object is basically a set of data, data structures, and methods combined together to form a single entity. An object is an instance of class. Therefore, a class is said to be a blueprint of an object.
Every object instantiated from a class will contain its own copy of member variables and member methods (unless they are declared static). Member methods are created to help an object process its member variable and take required actions.
The are three major steps involved while creating an object from a class:
1. Object Declaration
While declaring an object, you associate a variable name with that object.
Ex: Student myStud;
2. Object Instantiation
When you instantiate an object, you basically allocate space in the memory for that object. This is accomplished with the new operator.
Ex: Student myStud = new Student();
3. Object Initialization
When you initialize an object, you assign the object’s member variables with an initial set of values. This is accomplished using a constructor.
Ex: Student myStud = new Student( “John Travolta”, “34 Yrs”, “USA” );
The example given below creates a Java object named address from the class URL and initializes it with the value http://www.java-faq.com:
URL address = new URL( "http://www.java-faq.com" );
An object has 3 characteristic properties that also identifies it.
- Identity: An object name that differentiates it with other objects.
- State: At any point of time, the member variables of an object hold specific values. These values create an object state.
- Behavior: The methods defined within an object helps communicate and exchange data with other objects. These methods form the behavior of an object.
Many programming languages allow to create an exactly duplicate copy of another object. That is, the new copy will hold the same member variables and values from the object from which it is copied.
There are multiple ways to copy an object, which are Shallow Copy, Deep Copy, and Lazy Copy.
Different programming languages provide different methods to create a copy. In C++, an object can be copied with assignment operator or copy constructor. In Java, the same achieved by the clone() method. In Ruby On Rails, the methods clone() and dup() are used.
Lifetime of an Object
An object’s lifespan usually last from the time it is initialized to the time it is destructed or garbage collected. Different programming paradigms follow different algorithm to perform garbage collection. Therefore, even if an object is not used in the execution, it may still reside in the memory. Once the object is freed from execution, it has to be destructed by a garbage collector to free the held memory.