Java Part 4: Objects and Information Hiding - Objects and "this"
(Page 2 of 5 )
In the last article, we used the Number class to represent a simple object (remember, an object represents an instance of a class). In the class’s main() function, only one instance of the class was created:
public static void main( String[] args ){
Number number = new Number(); // single instance of Number class
number.addTo( 5 );
number.divideBy( 5 );
System.out.println( +number.getVal() );
System.exit(1);
}We could create more instances of the Number class like so:
Number number2 = new Number( 4 );This would create a new Number object called number2, with its “value” data member being set to 4. If we then used number2’s addTo() method,
number2.addTo( 5 );then number2’s value would increase to 9, and number’s value would remain unchanged, at 1.
As you can see from the examples above, we can have multiple instances of a single class that are entirely independent. This can be quite handy, and, if needed, we can pass on instance of a class to another. Let’s demonstrate this by writing another method for the Number class:
void addTwoNumbers( Number num ){
this.value += num.value;
}This method works on the object that it is a member of. The “this” statement represents the object that this method is a part of. Now, let’s demonstrate this function:
number.addTwoNumbers( number2 );would perform the operation:
number.value = number.value + number2.value;Now that I’ve described how to create a method for a class that will operate on itself, try writing similar methods for multiplying, subtracting and dividing from another Number class.
Next: Enforcing information hiding >>
More Java Articles
More By Chris Noack