Design and Simulation (Java language description) of the integer store unit

Recap

Before, we've done a generalization of the design and simulation of the storage unit , here, for example to a variable of type int and then practice it.

The storage unit Interger

I said before, if memory cells can also be said to be an ADT, then it should have the basic features I think are two:

  • Save / write
  • Taken / readout

By default initialization when you can be, you can also specify a specific initialValue.

Accordingly, it is abstracted into a class can be achieved.

According to this idea that, it is easy to design a storage unit integer friends.

To achieve the realization of class IntCell

public class IntCell {

    private int storedValue;

    public IntCell() {
        this(0);
    }

    public IntCell(int initialValue) {
        storedValue = initialValue;
    }

    public int read() {
        return storedValue;
    }

    public void write(int x) {
        storedValue = x;
    }

}

function test

Initialize a number, then one by one to read, write, read:

public class IntCellTest {
    public static void main(String [] args) {
        IntCell cell = new IntCell(7);
        System.out.println("Cell contents: " + cell.read());
        cell.write(5);
        System.out.println("Cell contents: " + cell.read());
    }
}

Test Results:

Cell contents: 7
Cell contents: 5
Published 570 original articles · won praise 1179 · Views 360,000 +

Guess you like

Origin blog.csdn.net/weixin_43896318/article/details/104452466