Working with Arrays of Objects with Java and NetBeans IDE - Overloading Methods in Java: Explanation
(Page 3 of 6 )
This section will explain the coding listed in the previous section. Let us start with the following:
int x=0;
int y=0;
Now, you can observe that I declared two fields/attributes for the class “MyCalc.” Proceeding further, we have the following:
public void setValues(int p) {
x = y = p;
}
The above method (setValues) simply accepts an integer as a parameter and assigns the same to both “x” and “y.” Proceeding further we have the following:
public void setValues(int m, int n) {
x = m;
y = n;
}
The above method is also similar to the previous one, except that it accepts two integers as parameters and assigns them to “x” and “y” respectively. Proceeding further we have the following:
public void setValues(MyCalc c) {
x = c.x;
y = c.y;
}
The above method simply accepts an object as a parameter and assigns the values available in its members to both “x” and “y.” I already explained “getSum()” in my previous articles.
Now, if we proceed to our “test” frame, we have the following initially:
MyCalc obj1 = new MyCalc();
MyCalc obj2 = new MyCalc();
obj1.setValues(10,20);
obj2.setValues(obj1);
From the above code fragment, I instantiated two objects: “obj1” and “ob2.” The third statement will call the method “setValues,” which accepts two integer parameters. The fourth statement will also call the method “setValues,” which accepts an object as a parameter.
We finally display the sum using the following:
int r;
r = obj1.getSum();
this.lblMsg.setText("Sum = " + String.valueOf(r));
r = obj2.getSum();
this.lblMsg2.setText("Sum = " + String.valueOf(r));
Next: How to Create Arrays of Objects in Java: Demo >>
More Java Articles
More By Jagadish Chaterjee