5.15.1. Defining Instance Methods

An instance method is a method that belongs to instances of a class, not to the class itself. To define an instance method, just omit static from the method heading.

Within the method definition, you refer to variables and methods in the class by their names, without a dot. For example, the previous page describes a method called getA that takes a parameter of type PairOfInts and returns that object's a variable. But it makes more sense to provide getA as an instance method of class PairOfInts. Here is an improved PairOfInts path with accessor getA and getB, and mutator methods setA and setB. These instance methods are marked public to allow them to be used in other classes. Since the variables are not intended to be accessed through methods, they are marked private.

  class PairOfInts
  {
     private int a;
     private int b;

     PairOfInts()
     {
        a = 0;
        b = 0;
     }

     PairOfInts(int aval, int bval)
     {
       a = aval;
       b = bval;
     }

     public int getA()
     {
       return a;
     }

     public void setA(int aval)
     {
       a = aval;
     }

     public int getB()
     {
       return b;
     }

     public void setB(int bval)
     {
       b = bval;
     }
  }

Warning about static methods

An instance method belong to a particular object. It can refer to instance variables and instance methods that belong to the same object. It can also use static variables and methods.

A static method belongs to the class, not to a particular object. So it cannot use instance variables or instance methods.


'This' reference

Within an instance method, you can refere to the object to which the method belongs as this. For example, method getA in class PairOfInts can be written as follows.

     public int getA()
     {
       return this.a;
     }
But this is more often used when you want to use the object as a whole without using one of its variables or methods.