Skip to content
This repository has been archived by the owner on Oct 18, 2022. It is now read-only.

Lesson 3

Scott Davis edited this page Nov 19, 2020 · 21 revisions

In this lesson, we will learn about getters and setters. We will also introduce Enums (enumerations). Finally we will learn to isolate our code into classes that have specific responsibilities.

Start by creating a new package folder called lesson03 (all lower case). Inside this folder create two classes. One called Lesson3Runner.java and the other called MultiCalculator.java.

The Lesson3Runner class will have our typical Run() method that collects user input to add and subtract numbers. However, this time we won't also do the calculations in this class. This time we will put all the logic for dealing with numbers in a separate class.

  • Lesson3Runner - responsible for asking the user questions, collecting inputs, and showing user the results
  • MultiCalculator - responsible for calculating totals, but has no idea where the numbers are coming from

Lesson 3

Assignment 1

First lets start with the MultiCalculator class. We need to create a public property on the Multicalculator class for both the first and second number. In Java, getters and setters are defined this way.

    private int number1;
    public int getNumber1() {
        return number1;
    }
    public void setNumber1(int val){
        number1 = val;
    }

Let's review this code. First, why write all this code? Can we just do this?

    public int number1;

Yes, yes you could, but Java developers all over the world would make fun of you. Actually, this practice of using a private class level variable, also referred to as a "backing variable" or "backing field" to hold a value, while using two separate methods to get and set the value is called a "best practice" and is a good habit to develop.

So, why use a getter and setter? There are many reasons, you might want to have a read-only property. If you did, you would only have a getNumber1 method and no set method. The backing field would be set somewhere else. You might want to do some validation on the number. Perhaps you want to make sure that Number1 can never be set negative. In that case you might have a getter and setter that looks like this.

    private int number1;
    public int getNumber1() {
        return number1;
    }
    public void setNumber1(int val){
        if (val < 0) {
            number1 = 0;
        } else {
            number1 = val;
        }
    }

There are several scenarios where you may want to add additional logic to a setter, or restrict the getter. It is simply a good idea to be consistent all the time, rather than sometimes using a getter and setter and other times just making your field a public variable.

Add this getter and setter to your MulitCalculator class. Create another getter and setter for Number2.

Note

You probably noticed that your getter method returns an int (integer), but the setter method returns void. What is void? Void means that the method will not return anything. If you are writing a method that does a job, but the code that called the method doesn't need a value back, you should have the method return void, which means it returns nothing.

Assignment 2

Create a method that will calculate the sum of these two numbers.

    public int calculate() {
        return getNumber1() + getNumber2();
    }    

What is going on with this method? Notice that this method does not take any parameters. Instead, it uses the properties we defined above. We now have nice and clean code in our calculator, and the MultiCalculator object could be used for many applications. Unlike the code we wrote in the first lesson, this code does not know anything about the command line. This class could be used on a robot, in a website, or a mobile application. All it does is calculates two numbers; it doesn't care where they came from.

Now that we have the ability to calculate the sum of two numbers, we need to write some code in our Lesson3Runner class.

We have already asked the user to enter two numbers before. We did it in Lesson 1. Good developers borrow code to speed up development when they can. Let's do the same. Go copy the Run and Add methods out of BasicCalculator in Lesson 1. You will also need to make a consructor for the MultiCalculator, and "new up" a Scanner object in the constructor.

You can delete code related to option 3 (continuously add numbers). We aren't going to do that in this lesson. Only add and subract.

Let's change this code to work with our new MultiCalculator object. You should be able to find this code in your Add method.

    System.out.println("Please enter the first number.");
    int number1 = scanner.nextInt();
    System.out.println("Please enter the second number");
    int number2 = scanner.nextInt();
    int sum = number1 + number2;

Next, change this code to use our new MultiCalculator object.

    MultiCalculator calc = new MultiCalculator();
    System.out.println("Please enter the first number.");
    int number1 = scanner.nextInt();
    calc.setNumber1(number1);
    System.out.println("Please enter the second number");
    int number2 = scanner.nextInt();
    calc.setNumber2(number2);
    int sum = calc.calculate();

Run Lesson 3 and make sure that it adds the two numbers. If you haven't yet, you'll need to add a new option to the main class to call the run() method in the Lesson3Runner.

You are probably thinking to yourself, this is dumb. It is more complicated and more code. You are correct that currently it is more code to add two number. However, you will see how this saves code as we start to add more options to subtract, multiply, and divide.

Assignment 3

Before we start working on more than just adding numbers, it is time to introduce a new concept: Enums.

Add this code to the bottom of your class. Make sure you add it before the last curly bracket ( { ), which denotes the end of the class.

    public enum Operation {
        ADD,
        SUBTRACT,
        MULTIPLY,
        DIVIDE
    }

This is an Enum. Enums are a fixed set of values. In Java, Enums are a special type of class. In this case, you can declare a variable of an enum type, like this:

    private Operation calcOperation = Operation.ADD;

A variable that is an enum type can only have a valid value that is equal to one of the predefined values. In this case a variable of type Operation, can only have 4 possible values. There is also something new here. The variable calcOperation is being initialized to the value of "ADD". This is another best practice. Most developers know that an integer initializes to 0 if an initial value is not set. But for an Enum, it is impossible to know which Enum value is default by just looking at the declaration.

Note

Enums are a special type of class, so their names start with a capital letter, like "Operation". Most Java developers prefer to declare the possible values as all uppercase. Not all java developers use this convention, but all caps seems to be most common.

Assignment 4

Create a getter and setter for calcOperation. You can use the private variable above to get you started. Use this line as your backing field, then add the getter and setter. You can reference Number1 as a sample, but instead of using "int" for the return type and parameter type, you will want to use Operation.

We won't use the setter until Assignment 6, but we will create it now.

Assignment 5

Update your calculate method to use the new calcOperation property to determine how the calculation should be done. This will get you started. Then add "else if" statements to do subtract, multiply, and divide.

    public int calculate() {
        if (getCalcOperation() == Operation.ADD) {
            return this.getNumber1() + this.getNumber2();
        } else {
            return 0;
        }
    }

Assignment 6

Finally, return to your Lesson3Runner class. We copied over the run() and add() methods. You may be tempted to add a subtract, multiply, and divide method, prompting users for number1 and number2 in each method. That would be quite a bit of extra (and redundant) code. Here is where making a calculator is going to save us some code. Make a new single method (and delete the add method) that prompts the user for both numbers and asks for them to select how to calculate the numbers. You can decide exactly how to write this code to ask for the operator to use, then set the "setCalcOperator" property on the MultiCalculator object. See if you can figure it out. Ask for help if you get stuck.

Check Your Work

Your final solution should look something like this class diagram. You should only have IO (input & output) in your Runner class. If you have input and print statements in your calculator, move them to your runner.

Lesson 3 Classes

Commit Your Code

(see Lesson 1)