A Fast Gateway to OOP in Java using NetBeans IDE - Accessing the members in “test”
(Page 4 of 5 )
Now, get back to the frame “test.java.” Double click on it to open, and finally double click on the button to open source view (which automatically generates an event for that button). Within the source view, modify your “buttonActionPerformed” in such a way that it looks like the following:
private void btnShowActionPerformed(java.awt.event.ActionEvent
evt) {
// TODO add your handling code here:
MyCalc obj = new MyCalc();
obj.x = 10;
obj.y = 20;
int r = obj.getSum();
this.lblMsg.setText("Sum = " + String.valueOf(r));
}
Once you execute your application (by pressing F5), you will be able to see a window with a button “Show.” Once you click on it, it shows the message “Sum=30” (Fig08)

Now, let us go through the code given above. Let us look at the following statement:
MyCalc obj = new MyCalc();
The above statement simply creates an “instance” of the class “MyCalc.” An “instance” is nothing but some memory area, which gets occupied in RAM to hold all the members of class (along with their values).
In this case, the name of the “instance” is “obj.” We can also call an “instance” as “object.” An “instance/object” holds all the members of a particular class in memory. Thus the same “instance/object” (obj) internally contains the members “x,” “y” and “getSum.” To access any member in an “instance,” we need to first write the name of the instance (obj) and the name of the member (x,y,getSum), separated with a period (dot).
The same process is being followed in the following:
obj.x = 10;
obj.y = 20;
We are simply assigning some values to the members available in the instance “obj.” Since “getSum” is a method which returns an “int” value, we need to assign it to the same type of variable. And thus we have the following:
int r = obj.getSum();
And finally, we display the output using the following statement:
this.lblMsg.setText("Sum = " + String.valueOf(r));
From here on, I shall stick to using the word “object” rather than “instance” (anyway, they mean the same thing).
Next: Working with more than one object >>
More Java Articles
More By Jagadish Chaterjee