next up previous
Next: 3.6 Computer Graphics Up: 3 Example Models Previous: 3.4 Computer Organization

3.5 Object Programming

After taking a course in object programming, students sometimes lack a conceptual understanding of object programming which is independent from the syntax of the object programming language used in the course. The following model has been used to teach object programming concepts. J locales are used to build objects which combine both data structure and code. The J object programming system has a similar conceptual basis.

make_z_ =: 0 !: 0 @ <
for_effect_only_z_ =: monad def '''unspecified'''
invalid_method_name_indicator_z_ =: 'unknown'
root_object_z_ =: monad define
('method' ; 'value') =. 2 take y.
if. method -: 'type'
  do. 'root object'
  else. 'In root object: ',method,': Invalid method name.'
end.
)

The following file is a definition of a stack object which inherits its printing method from a printing object.

NB. The stack object template which inherits a print method

data =: ''

stack_z_ =: monad def 0
('method' ; 'value') =. 2 take y.
if. method match 'type'
    do. 'stack'
  elseif. method match 'emptyp'
    do. 0 = tally data
  elseif. method match 'push'
    do. for_effect_only data =: (box value) , data
  elseif. method match 'top'
    do. if. 0 = tally data
          do. 'top:  stack is empty'
          else. open first data
        end.
  elseif. method match 'pop'
    do. if. 0 = tally data
          do. 'pop:  stack is empty'
          else. for_effect_only data =: rest data
        end.
  elseif. method match 'size'
    do. tally data
  elseif. method match 'print'
    do. if. 0 = tally data
          do. 'print: stack is empty'
          else. for_effect_only display 'top of stack'
                print 'print' ; box data
        end.
  elseif. 1
    do. root_object method ; value
end.
)

The Printing object:

NB. The stack and queue print object

print_z_ =: monad define
('method' ; 'value') =. 2 take y.
if. method match 'type'
    do. 'print'
  elseif. method match 'print'
    do.
    while. 0 < tally value
      do. for_effect_only display open first value
          value =. rest value
    end.
  elseif. 1
    do. base method ; value
end.
)

Following is an interactive session which makes a stack object, named s, and then pushes and pops items on the stack.

   make_s_ 'stack1.object.ijs'
   stack_s_ <'type'
stack
   stack_s_ <'size'
0
   stack_s_ <'age'
In root object: age: Invalid method name.
   stack_s_ 'push' ; i. 10
unspecified
   stack_s_ <'size'
1
   stack_s_ 'push' ; 'Some text'
unspecified
   stack_s_ <'size'
2
   stack_s_ <'top'
Some text
   stack_s_ <'print'
top of stack
Some text
0 1 2 3 4 5 6 7 8 9
   stack_s_ <'pop'
unspecified
   stack_s_ <'top'
0 1 2 3 4 5 6 7 8 9


next up previous
Next: 3.6 Computer Graphics Up: 3 Example Models Previous: 3.4 Computer Organization
2003-12-20