Java Programming

6.2 Class Objects

As pointed out earlier, an object in java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object.

In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The ‘new’ key word is used to create the object.
Initialization: The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object.

Example of creating an object is given below:
Rectangle rect;
rect = new Rectangle();

In the first statement we declared the object rect. it declares a variable to hold the object reference and in second we instantiated the object which actually assigns the object reference to the variable.
variable rect is now an object of the Rectangle class.

Accessing class members
Now that we have created objects, each containing its own set of variables, we should assign values to those variables in order to use them in our program.
Remember, all variables must be assigned values before they are used.
Since we are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator as shown below:
objectname.variablename = value; objectname.methodname(parameter-list);

Here objectname is the name of the object, variablename is the name of the instance variable inside the object that we wish to access, methodname is the method that we wish to call, and parameter-list is a comma separated list of “actual values” (or expressions) that must match in type and number with the Parameter list of the methodname declared in the class.

The instance variables & method of the Rectangle class may be accessed and assigned values as follows:
rect1.width=15
rect1.length=20;
rect2.width=24;
rect2.length=34;
rect1.area();

Download for more knowledge

https://play.google.com/store/apps/details?id=ab.java.programming

Leave a comment