up previous next contents
Next: this Up: Classes and objects Previous: Constructors   Contents

Subsections

Methods

  • Here is a sample method for the Body class. The method name is toString.
      public String toString()
      {
          String desc = idNum + " (" + name + ")";
          if orbits != null)
          {
              desc += " orbits " + orbits.toString();
          }
          return desc;
      }
    
  • Returns type String.
  • Methods contain the code that understands and manipulates an object's state.
  • Methods are invoked as operations on an object using the . (dot) operator.
  • Each method takes a specific number of parameters.
  • Each parameter has a specified type - primitive or object.
  • Methods also have a return type (or void).

Parameter values

  • All parameter methods are "pass by value".
  • Values of a parameter are copies of the values in the invoking method.
  • When the parameter is an object, the object reference is passed by value.
  • End result: primitives cannot be modified in methods, objects can.

Using methods to control access

  • If data fields (attributes) are public, programmers can change them.
  • Generally want to hide the data from programmers that will use the class.
  • If programmers can access a class's fields directly, you have no control over what values they can assign.
  • In the Body example, nextIDshould be private.
  • If necessary, you should provide get methods that allow programmers to determine the current field value, and set methods to modify the value. These are called accessors (get) and mutators (set).


up previous next contents
Next: this Up: Classes and objects Previous: Constructors   Contents