Constructing and Initializing Objects in JAVA Language

Harsh Gupta - Tech Writer
Java is a pure object-oriented, general-purpose and high-level language. As Java is pure object-oriented, it deals with each real world problem with the help of object and classes. Here, we are explaining how the reference is made to an object and how the member variables of the object are initialized. We can create object of a particular class by following syntax:

= new ;

But sometimes you place some variables as arguments with classname attached with keyword "new" like:

Mydate obj1=new Mydate (22, 7, 1964);

Using the keyword "new" cause the following:

First, the space for new object is allocated and initialized to the form of 0 or null. In the java programming language, this phase is invisible to ensure that you cannot have an object with random values in it.

Second, any explicit initialization is performed.

Third, a constructor, which is a special method, is executed. Arguments passed in the parentheses to new be passed to the constructor (22, 7, 1964).

Finally, the return value from the new operation is a reference to the new object in heap memory. This reference is stored in the reference variable.

Memory allocation and layout:

In the method body, the following declaration allocates storage only for the reference as

Mybirth ????

The word new in the following example implies allocation and initialization of storage as:

Mybirth ????

Day 0

Month 0

Year 0

Explicit attribute initialization:

If you place simple assignment expressions in your member declarations, you can initialize members explicitly during construction of your object. In the Mydate class in this example, initializing all the three attributes explicitly declared, as:

Mybirth ????

Day 1

Month 1

Year 2000

Explicit initialization

Executing the constructor:

The final stage of initializing a new object is to call the constructor. The constructor enables you to override the default initialization. You can perform computations. You can also pass arguments into the construction process so that the code that requests the construction of the new object can control the object it creates.

The following example calls the constructor as like below:

Mydate obj1= new Mydate (22, 7, 1964);

Mybirth ????

Day 22

Month 7

Year 1964

CONSTRUCTOR CALL

Assigning a variable:

The variable assignment then sets up the reference variable obj1 in this example, so that it refer properly to the newly created object as shown below:

Mydate obj1=new Mydate (22, 7, 1964);

Mybirth 0x01abcdef

Day 22

Month 7

Year 1964
reference variable assignment

Published by Harsh Gupta - Tech Writer

I am a part time freelancer and writing is my hobby Some of my websites: http://www.GenericArticles.com http://www.JailBreakingiPhone.com  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.