Each object created will have its own copies of the fields defined in its class. The fields of an object are called instance variables. The values of the instance variables in an object comprise its state. Two distinct objects can have the same state, if their instance variables have the same values. The methods of an object define its behavior. These methods are called instance methods. It is important to note that these methods pertain to each object of the class. This should not be confused with the implementation of the methods, which is shared by all instances of the class. Instance variables and instance methods, which belong to objects, are collectively called instance members, to distinguish them from static members, which only belong to the class. Static members are discussed in Section 1.5.
Objects communicate by message passing. This means that an object can be made to exhibit a particular behavior by invoking the appropriate operation on the object. In Java, this is done by calling a method on the object using the binary infix dot '.' operator. A method call spells out the complete message: the object that is the receiver of the message, the method to be invoked, and the arguments to the method, if any. The method invoked on the receiver can also send information back to the sender, via a return value. The method called must be one that is defined for the object.
CharStack stack = new CharStack(5); // Create a stack stack.push('J'); // (1) Character 'J' pushed char c = stack.pop(); // (2) One character popped and returned: 'J' stack.printStackElements(); // (3) Compile time error: No such method in CharStack
The sample code above invokes methods on the object denoted by the reference variable stack. The method call at (1) pushes one character on the stack, and the method call at (2) pops one character off the stack. Both push() and pop() methods are defined in the class CharStack. The push() method does not return any value, but the pop() method returns the character popped. Trying to invoke a method printStackElements() on the stack results in a compile-time error, as no such method is defined in the class CharStack.
The dot '.' notation also can be used with a reference to access fields of an object. The use of the dot notation is governed by the accessibility of the member. The fields in class CharStack have private accessibility, indicating that they are not accessible from outside the class:
stack.topOfStack++; // Compile time error: topOfStack is a private field.