Monday, 4 September 2017

Object representation in memory



   Object Representation in memory.

 
When you create an object of a class the memory will gets allocated to the new object created and the object will be holding all the fields and method defined in the class.
For example consider the picture below.



Consider a class defined which has fields; Filed-1, Fiels-2, Field-3…..Field-n and method defined inside the same class.

 
When you create a new object of the class memory gets allocated for the object which has enough memory equal to the sum of all memory allocated for fields and methods in the class for which the object is created so that it can store and process all the members and fields defined in the class.

So whenever we access a member of a class from other class we always access those using objects we created for that class by using dot operator(.). 
 
Another example below shows a class Rectangle with fields height , width and has a method named getArea() whose return type is an integer. The class RectangleMain is the class which contains the main method.


 
In the main method of class RectangleMain we created an object named “obj” of class Rectangle.

 
To access the method getArea() we called the method of the Rectangle class named getArea() from the class RectangleMain by using dot operator(.) . The compiled output of the above programs is given below.


 
Note: We compile the class which includes the Object definition. So in this case the Object “obj” is defined inside the main method of RectangleMain class.

 
When the object “obj” of class Rectangle is created the new operator allocated space for the object “obj” and calls the constructor Rectangle() to initialize the fields present in the class Rectangle.
The below picture shows the following.


As the picture shows when you create an object of class Rectangle the new operator invokes the constructor Rectangle() to create and initialize the object.
 
Then the reference of the object created is passed to the variable obj whose type is of Rectangle.
 

So now the “obj” points to the object of class Rectangle.
 

No comments:

Post a Comment

             The `this` keyword in java The this keyword in java can be used for different purposes. Some of these are listed below. ...