Overriding toString()
| Code | Output |
|---|---|
final Shape shape =
new Shape(2.0, 3.0); // Center coordinates
IO.println(shape); |
inherit.Shape@37d31475 Desired: (2.0|3.0) |
toString() | Code | public class Shape {
private int x, y;
...
@Override public String toString() {
return "(" + x + "|" + y + ")";
}
}IO.println(new Shape(2.0, 3.0)); |
|---|---|
| Output | (2.0|3.0) |
| Code | // Center coordinates (2|3), width==5 and height==7 final Rectangle r = new Rectangle(2.0, 3.0, 5.0, 7.0); IO.println(r); |
|---|---|
| Output |
Desired: (2.0|3.0), width=5.0, height=7.0 |
| Code | public class Circle extends Shape {
private double radius;
...
@Override public String toString() {
return super.toString() + ", radius=" + radius;
}
}IO.println(new Circle(2.0, 3.0, 7.0)); |
|---|---|
| Output | (2.0|3.0), radius=7.0 |
No. 179
String vs.
StringBuffer
|
Q: |
Consider two
Strangely
Explain this different behaviour. TipTake a closer look at the |
||||||||
|
A: |
public boolean equals (Object anObject) Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Overrides: equals in class Object Parameters: anObject - The object to compare this String against Returns: true if the given object represents a String equivalent to this string, false otherwise In a nutshell: The superclass The public boolean equals (Object obj)
Indicates whether some other object is "equal to" this one.
...
Parameters:
obj - the reference object with which to compare.
Returns:
true if this object is the same as the obj argument; false otherwise.The comparison is thus by object identity rather than by content. |
No. 180
Alternate implementation of opposite directions
|
Q: |
Provide a different implementation of your |
||
|
A: |
We observe the following ordinal values:
We are thus require implementing an integer shift of (0, 1, 2, 3, 4, 5, 6, 7) → (4, 5, 6, 7, 0, 1, 2, 3) by four places: public Direction opposite() { return values()[(ordinal() + 4) % 8]; } |
