This code is ready to run -- just copy it into a file named SmartInteger.java.
public class SmartInteger {
private int n;
/** Returns new SmartInteger on <aNumber> */public SmartInteger(int aNumber) {
this.n = aNumber;
}
/** Returns friendly string of this object */public String toString() {
return "n: " + this.n;
}
/** Returns square of this number */public int squared() {
return this.n * this.n;
}
/** Returns cube of this number */public int cubed() {
return this.n * this.n * this.n;
}
/** Returns the square root (rounded) of this number */public int squareRoot() {
return (int)Math.round(Math.sqrt(this.n));
}
/** Returns the quotient (rounded) of this number divided by the passed divisor */public int dividedBy(int divisor) {
return (int)Math.round((double)this.n / (double)divisor);
}
}
Below we send some messages to a SmartInteger object.
This code is ready to run -- just copy it into a file named SmartInteger.java.
For example, the code doc tells us that the SmartInteger object type (class) understands the message squared -- thus we send it as shown below.
public class SmartInteger {
private int n;
/** Returns new SmartInteger on <aNumber> */public SmartInteger(int aNumber) {
this.n = aNumber;
}
/** Returns friendly string of this object */public String toString() {
return "n: " + this.n;
}
/** Returns square of this number */public int squared() {
return this.n * this.n;
}
/** Returns cube of this number */public int cubed() {
return this.n * this.n * this.n;
}
/** Returns the square root (rounded) of this number */public int squareRoot() {
return (int)Math.round(Math.sqrt(this.n));
}
/** Returns the quotient (rounded) of this number divided by the passed divisor */public int dividedBy(int divisor) {
return (int)Math.round((double)this.n / (double)divisor);
}
}