7.2. Methods

In the previous example, virtually identical code was repeated several times to update the x and y instance variables of the two ships. This approach represents poor coding style, not only because the initial repetition takes time, but, more importantly, because updates require changing code in multiple places. To solve this problem, classes can have functions associated with them, not just data, as in Listing 7.2. Java calls them “methods” as in Lisp/CLOS rather than “member functions” as in C++. Notice that, unlike the case with C++, instance variables can be directly initialized in the declaration, as with

public double x=0.0;

Note also the use of public and private. These modifiers are discussed in more detail in Section 7.11 ...

Get Core Web Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.