\(9.2.\)Object-based Programming

1.Object-oriented programming

  When designing an abstraction, we

  1. Consider what kind of data do we want to store about and the objects that this class is supposed to represent.

    • In our case, we need to store numerator and denominator.
  2. We store these values into integer type of field.

  3. The only way to access field values from outside the class is through accessor methods, so we create accessors to facilitate access.

  1. Then we write a constructor to create new objects. We create the object and return it to the base address.

    • this is a standard reference to the current object. It is actually the base address of the current object in the host RAM.

    • One of the rules of the game is that a Jack constructor must

      • return the base address.
      • return an object of the type of the surrounding class or the class to which this constructor belongs.
      • In Jack, every subroutine must always terminate with return command.
  2. We create several methods as we wish, this is quite simple so we skip this part.

  3. We create dispose method:

    • The method is implemented using a call to the host operation system. We call the OS routine deAlloc, which takes an address in memory and disposes the memory block that begins in this address.
    • This is important to Jack, because Jack has no garbage collection services, so it's up to the programmer to do this.

2.Object representation

  In client's view:

  • Each fraction is represented by a block that includes all the field values of the current object.
  • We have a reference to each of these blocks, which is the name of the variable.

  In the host RAM:

  • Some area of it is designated to represent the the stack of the currently running application.
  • The stack is used to store variables.
  • We have the heap where we represent objects and arrays.

 We see that we have a variable a which contains the number 15087. If we treat this variable as a pointer and look up this address in the RAM, we see that the number after the 2 is 3. This two numbers comprise the memory block that represents our first object.

  How does this representation is established? The secret is that: when the compiler is going to compile your constructor, it would

  1. Inject some calls to the operating system.
  2. These calls are going to find available memory and allocate it to the object that was just constructed.