Monday, October 16, 2006

OOP Part 2 - Objects And Variables

Instantiating an Object

An Object is an instance of a Class. After creating an Object, you can access the member variables and methods of the object and assign values to them. An Object is declared in the same way that a variable of a primitive type is declared.

String sampleStr; //This code is used to define an object name of String type.

You can define a varibale that will be used to refer to an object or an instance of a class.

When you create an object, you need to assign memory to the object. This is done using the new operator. The new operator is followed by the class name and parentheses. The syntax for creating an object is displayed below:

class_name variable_name = new class_name();
Example: Test aTest = new Test();

This code is used to create an instance of the Test class. The variable aTest is decleared. Notice that this is an arbitary variable name. This variable is used to refer to the instance of the Test class. You can also state that the name of this particular Test instance is aTest.

When multiple instances are created, each instance maintains a seperate copy of the member variables of the class.

Post is not yet complete

No comments: