Identify the parts (instance variables, constructor, getters and setters, operators, helpers) in the code below:
public class Calculator {
private double left;
private double right;
public Calculator(double left, double right) {
this.left = left;
this.right = right;
}
public double getLeft() {
return left;
}
public double getRight() {
return right;
}
public void setLeft(double number) {
left = number;
}
public void setRight(double number) {
right = number;
}
public double add() {
return left + right;
}
public double subtract() {
return left - right;
}
public double multiply() {
return left * right;
}
public double divide() {
return left / right;
}
public static void main(String[] args) {
Calculator calc = new Calculator(10, 5.6);
System.out.println(calc.add());
System.out.println(calc.subtract());
System.out.println(calc.multiply());
System.out.println(calc.divide());
}
}Use the keyword static for methods or variables that belong to the class itself rather than instances/individual objects
Instance Variables vs Class Variables (use static) - Instance variables are unique to each object, while class variables are shared across all instances of a class.
We can have static methods in any class, here’s an example – we will add this static method to our Calculator class:
Here’s how we use it (note the difference between calling an object method and a static class method):
When we add the keyword static to a variable in a class, that becomes a class variable (as opposed to instance variable). Let’s add some code to the main method in our Calculator class, two create two objects:
Calculator calc = new Calculator(10, 5.6);
Calculator anotherCalc = new Calculator(4, 2);
System.out.println(calc.add());
System.out.println(anotherCalc.add());
anotherCalc.setLeft(10);
System.out.println(calc.add());
System.out.println(anotherCalc.add());Run the code and notice the output. The .setLeft(10) method call only changed the output for anotherCalc object. Change the left variable to static – how do the results change?