Classes

Objective #1: Understand how classes are used in Java.

Objective #2: Create a new class by adding an instance method to an existing class.

Objective #3: Develop a whole new class by typing out its instance variables, instance methods, and constructors from scratch.

Objective #4: Add public accessor methods to a class so client programmers can access instance variables of an object.

Objective #5: Add modifier methods to a class so client programmers can modify instance variables of an object.

Objective #6: Add "interesting" methods to a class.

It is legal to access myAge from within the Bug class even though it is private.

In a client program this code segment would be used to call the computeLife instance method

Bug nemo = new Bug();
nemo.setAge(5);
System.out.println(nemo.computeLife()); // displays 4 since 9 minus 5 is 4


Note that the computeLife method could be written in this way

   public int computeLife()
   {
      int num = 0;    // local variable temporarily used to store the life expectancy
      num = BUG_LIFE_EXPECTANCY - this.myAge;
      return num;
   }


since the keyword this can be used within a regular class to refer to the implicit parameter that is calling the method (i.e. nemo in this case)

The computeLife method could also be written by using the accessor method instead of directly accessing the myAge instance variable but notice that the empty parentheses are requird with getAge() since it is a method:

   public int computeLife()
   {
      int num = 0;    // local variable temporarily used to store the life expectancy
      num = BUG_LIFE_EXPECTANCY - getAge();
      return num;
   }


The computeLife method could also be written without the declaration statement of the local variable named num and this can be used with instance methods just as it is used with instance variables:

   public int computeLife()
   {
      return BUG_LIFE_EXPECTANCY - this.getAge();
   }