Search | | Contact Us | Resource Center Login | Home|

In the following program, if you change the declaration of method "m" by removing the word "static" from line 4, what other changes must you make?

  1  namespace n
  2    class c
  3      public static chan, int
  4      public static method m, void
  5      proc
  6        writes(chan, "hello")
  7      end
  8    endclass
  9  endnamespace
 11  main
 12  proc
 13      open(1,o,"TT:")
 14      c.chan = 1
 15      c.m()
 16  end
  1. Also remove "static" from line 3
  2. Change "c" in line 14 to an instance reference
  3. Change "c" in line 15 to an instance reference
  4. All of the above
  5. a and b only
  6. b and c only
  7. a and c only

When you invoke a static method, you call it as a member of the class as in the example above. When you call an instance (non-static) method, it must have an instance on which to operate. You must therefore first create an instance, assign it to an object variable, and then call the method on that reference instead. Thus, (c) is definitely included -- and (e) is ruled out.

If we change the member variable "chan" to an instance variable (non-static) as well, then we must also change any reference to it to operate on an instance reference. Thus, (a) and (b) are linked inextricably together.

The question remains whether (a) and (b) are required. They are not, because an instance method can still access static data in the class.

Thus, the correct answer is (c). Here is the routine rewritten accordingly:

namespace n
  class c
    public static chan, int
    public method m, void
	 writes(chan, "hello")

    i ,@c
    c.chan = 1
    i = new c()

A more important question is: when does it make sense for a method to be static versus non-static? Static methods are essentially the same as functions and subroutines, in that they do not implicitly refer to any single object. Instance methods, on the other hand, are intended to operate on a specific collection of data that comprises a unique object. They resemble subroutines and functions that share states with other routines, but because you can have more than one instance of an object, you can also have more than one set of states.

When a method acts on the states that belong to an object (its instance data), then that method should properly be an instance method. In our example above, if we leave chan as a static member, then there is no apparent reason to make method "m" an instance method. However, if we wanted to preserve a different channel per instance of class "c", then we would make chan non-static as well as method "m", so the state (channel) would be bound to each object and the method would act upon only that object's state.

More information about News and Events

Contact Synergex to learn more about  News and Events