Java Reference
In-Depth Information
To access class variables, you use the same dot notation as with instance variables. To
retrieve or change the value of the class variable, you can use either the instance or the
name of the class on the left side of the dot. Both lines of output in this example display
the same value:
FamilyMember dad = new FamilyMember();
System.out.println(“Family's surname is: “ + dad.surname);
System.out.println(“Family's surname is: “ + FamilyMember.surname);
Because you can use an instance to change the value of a class variable, it's easy to
become confused about class variables and where their values are coming from.
Remember that the value of a class variable affects all its instances. For this reason, it's a
good idea to use the name of the class when you refer to a class variable. It makes your
code easier to read and makes strange results easier to debug.
Calling Methods
Calling a method in an object is similar to referring to its instance variables: Dot notation
is used. The object whose method you're calling is on the left side of the dot, and the
name of the method and its arguments are on the right side of the dot:
myCustomer.addToOrder(itemNumber, price, quantity);
Note that all methods must have parentheses after them, even if the method takes no
arguments:
myCustomer.cancelAllOrders();
Listing 3.3 shows an example of calling some methods defined in the String class.
Strings include methods for string tests and modification, similar to what you would
expect in a string library in other languages.
LISTING 3.3
The Full Text of StringChecker.java
1: class StringChecker {
2:
3: public static void main(String[] arguments) {
4: String str = “Nobody ever went broke by buying IBM”;
5: System.out.println(“The string is: “ + str);
6: System.out.println(“Length of this string: “
7: + str.length());
8: System.out.println(“The character at position 5: “
9: + str.charAt(5));
10: System.out.println(“The substring from 26 to 32: “
11: + str.substring(26, 32));
 
Search WWH ::




Custom Search