Java Reference
In-Depth Information
Here is an alternative version:
// Returns a String representation of this Name.
public String toString() {
return getNormalOrder();
}
14. A constructor is a special method that creates an object and initializes its state. It's
the method that is called when you use the new keyword. A constructor is declared
without a return type.
15.
The constructor shouldn't have the void keyword in its header, because con-
structors have no return type. The header should be
public Point(int x, int y) {
The fields x and y shouldn't have their types redeclared in front of them. This
bug causes shadowing of the fields. Here are the corrected lines:
x = initialX;
y = initialY;
16. // A Name object represents a name such as "John Q. Public".
public class Name {
String firstName;
char middleInitial;
String lastName;
// Initializes a new Name with the given values.
public Name(String initialFirst, char initialMiddle,
String initialLast) {
firstName = initialFirst;
middleInitial = initialMiddle;
lastName = initialLast;
}
// The name in normal order such as "John Q. Public".
public String getNormalOrder() {
return firstName + " " + middleInitial +
". " + lastName;
}
// The name in reverse order such as "Public, John Q.".
public String getReverseOrder() {
return lastName + ", " + firstName +
" " + middleInitial + ".";
}
}
Search WWH ::




Custom Search