Overriding toString()
Code | Output |
---|---|
package inherit; public class Run { public static void main(String[] args) { final Shape shape = new Shape(2.0, 3.0); // Center coordinates System.out.println(shape); |
inherit.Shape@37d31475 Desired: (2.0|3.0) |
toString()
Code | Output |
---|---|
|
(2.0|3.0) Desired: Rectangle at (2.0|3.0), width= 3.0, height=4.0 |
public class Circle extends Shape {
/**
* Creating a circle of given center and radius
* @param x Center's x component.
* @param y Center's y component.
* @param radius The circle's radius.
*/
public Circle(double x,double y, double radius) {
super(x, y);
this.radius = radius;
}
@Override public String toString() {
return "Circle at " + super.toString() +", radius= " + radius;
}
private double radius;
}
No. 163
String
vs.
StringBuffer
Q: |
Consider two
Strangely instances of String behave differently:
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: Two instances of String will be compared for
equality character by character. The superclass In class 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. Thus two instances of |
No. 164
Alternate implementation of opposite directions
Q: |
Provide a different implementation of your |
||
A: |
We observe the following ordinal values:
We are thus left implementing an integer shift
|