Monday, September 15, 2008

Instantiating an Object in Java

The new operator instantiates a class by allocating memory for a new object of that type. new requires a single, postfix argument : a call to a constructor. Each Java class provides a set of constructors used to initialize new objects of that type. the new operator creates the object, and the constructor initializes it. Here’s an example of using the new operator to create a rectangle object:

new rectangle(100,200);

Here, rectangle (100,200) is argument to new. The new operator returns a reference to newly created object. This reference can be assigned to a variable of the appropriate type, as shown here:

rectangle rect = new rectangle(100,200);

After this statement, rect refers to a rectangle object whose origin is at (0,0), width is 100, and height is 200.

No comments: