Java Object

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.

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.

Java Online Test


« Previous Tutorial Next Tutorial »