TurkuBasicOOPinJava / Week 4: Writing classes /11B. Write class Calculator
KaiquanMah's picture
Create 11B. Write class Calculator
7f20352 verified
raw
history blame
1.91 kB
Write the class Calculator. The class must have the following properties:
Private integer type attribute result
a void type method add(int number), which adds the given number to the result
Methods subtract(int number) and multiply(int number) that work in a similar way.
The method inverse(), which converts the result to the inverse (e.g. 3 is converted to -3)
Get method getResult(), which returns the current result
Note! Since the test class is public, the class Calculator cannot be. So do not use the attribute public in its definition.
import java.util.Random;
import java.lang.reflect.Field;
public class Test{
public static void main(String[] args){
}
}
class Calculator {
private int result;
// removed 'static'
// 'static' means the method belongs to the class, not an object instance of the class
// removing 'static' allows us to use 'this' to access instance variables/attributes
public void add(int number) {
this.result += number;
}
public void subtract(int number) {
this.result -= number;
}
public void multiply(int number) {
this.result *= number;
}
public void inverse() {
this.result = -1 * this.result;
}
public int getResult() {
return this.result;
}
}
Testing class Calculator...
Constructor Calculator() found, object created!
Checking attribute...
Attribute result found!
Attribute type: int
Attribute private: true
Testing methods....
Calling add(12)
Result is now: 12
Calling add(2)
Result is now: 14
Calling add(12)
Result is now: 26
Calling subtract(3)
Result is now: 23
Calling subtract(23)
Result is now: 0
Calling subtract(12)
Result is now: -12
Calling multiply(-1)
Result is now: 12
Calling multiply(-1)
Result is now: -12
Calling multiply(6)
Result is now: -72
Calling inverse()
Result is now: 72
Calling inverse()
Result is now: -72