As already discussed that objects have states and behaviours. An object is an instance of a class.
Now let's know how to declare objects.
Declare Objects in Java
When you create a class, you are creating a new data type. You can use this type to declare objects of that type.
On the other hand, obtaining objects of a class is a two-step process.
- You must declare a variable of the class type. However, this variable does not define an object. Rather, it is a variable that can refer to an object.
- You must acquire real, physical copy of the object and assign it to that variable. You can do this using the new operator.
The new operator dynamically allocates the memory for an object and returns a reference to it. This reference is, more/less, the address in memory of the object allocated by the new. This reference is then stored in the variable. Thus, in Java, all the class objects must be dynamically allocated.
In the preceding example, a line similar to the following is used to declare an object of type Box :
Box mybox = new Box();
This statement combines the two steps just discussed. It can be rewritten like this to show each and every step more clearly :
Box mybox; // declare a reference to object mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of the type Box. At this stage, mybox does not however refer to an actual object. The next line allocates an object and then assigns a reference to it to the mybox. After the second line executes, you can use mybox as if it were a Box object. But actually, mybox holds memory address of actual Box object.
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube