Java Chapter 8 - Classes

8.1 Basic Class

Classes are what makes Java an object-oriented programming (OOP) language.  OOP allows you to create objects that contain both data and methods (functions).  A class defines an object - the attributes and functions.  From there, you can create objects from the class.

For example, a class could define an Enemy in a game as having variables Type, Speed, Health, X and Y location along with functions to Move and Attack.  You can then create instances (objects) of the Enemy.

Enemy Class Example
Properties (variables) Methods
EnemyType
Speed
Health
X, Y
Move()
Attack()


Another example is a class that defines a pair of dice.  The data for the object is the numbers that are showing on top.  The method for the object is to roll the dice. 

Pair of Dice Class Example
Properties (variables) Methods
Dice1Value
Dice2Value
Roll()


Once a class is defined, then the main program can create one or more instances (objects) from class.  Below is an example of declaring and using an instance of the Dice class:

   myDice Lucky = new myDice();                                    // Declare an instance of myDice named Lucky
   Lucky.Roll();                                                   // Roll the dice
   System.out.println(Lucky.Dice1Value + " " + Lucky.Dice2Value);  // Print the value of the dice


The program below defines a cube class (myCube).  The data consists of the length, width, and height.  It has one method that returns the volume of the cube.  The main program defines an instance of MyCube.  The MyCube class initializes values of length, width, and height to zero.

myCube Class
public class cube1
{
   public static void main(String[] args)
   {
      myCube Valerie = new myCube();

      Valerie.Length = 3;
      Valerie.Width = 2;
      Valerie.Height = 6;

      System.out.println("Valerie has volume of " + Valerie.getVolume());
   }
}

class myCube
{
   // Class variables are declared and initialized to zero
   public int Length = 0, Width = 0, Height = 0;

   int getVolume()
   {
      return Length * Width * Height;
   }
}
Output
Valerie has volume of 36

8.2 Constructors

In the preceding program, the Length, Width, and Height variables are initialized to zero when they are declared.  An alternative way to initialize variables is from within a constructor.  A constructor is a method with the same name as the class, and is executed when an instance of a class is created.  In addition to initializing variables, can perform additional setup and be used to accept parameters from the main program when an instance of the class is created:

myCube Valerie = new MyCube(3,3,2);    // Send 3,3,2 as parameters to the new MyCube named Valerie

The program below allows instances of MyCube to be declared with or without parameters.  Remember that when there are multiple methods of the same name that take different parameters, it's called overloading the methods.

myCube Class with Constructors
public class cube2
{
   public static void main(String[] args)
   {
      // Vicky initialized without using parameters.
      // This constructor sets defaults: Length=1, Width=1, Height=1
      myCube Vicky = new myCube();
      System.out.println("Vicky has volume of " + Vicky.getVolume());

      // Valerie initialized with parameter values Length=3, Width=3, Height=2
      myCube Valerie = new myCube(3,3,2);
      System.out.println("Valerie has volume of " + Valerie.getVolume());
   }
}

class myCube
{
   public int Length, Width, Height;

   // Constructor used if no parameters are sent. It sets default values.
   public myCube()
   { 
      Length = 1;  Width = 1;  Height = 1;
   }
   // Constructor used when parameters are sent to initialize variables
   public myCube(int L, int W, int H)
   {
      Length = L;  Width = W;  Height = H;
   }

   public int getVolume()
   {
      return Length * Width * Height;
   }
}
Output
Vicky has volume of 1
Valerie has volume of 18

 

8.3 Data Hiding and Encapsulation

Encapsulation means that you combine the variables with the methods that act on them.  The class variables are hidden (secured) from the main program or other classes.  They are made private so other classes have no access to them.  Get and Set methods can be written to allow access to the variables.  Data hiding provides you with control over data access and manipulation.

Data Hiding - Class Variables made Private
public class cube1
{
   public static void main(String[] args)
   {
      myCube Valerie = new myCube();

      Valerie.setLength(3);
      Valerie.setWidth(2);
      Valerie.setHeight(4);

      System.out.println("Valerie has volume of " + Valerie.getVolume());
   }
}

class MyCube
{
   private int Length, Width, Height;   // main program cannot access private variables

   void setLength(int L)  // access method to set Length
   {  Length = L;  }

   void setWidth(int W)  // access method to set Width
   {  Width = L;  }

   void setHeight(int H)  // access method to set Height
   {  Height = H;  }

   getLength()    // access method to set Length
   {  return Length;  }

   getWidth()    // access method to set Width
   {  return Width;  }

   getHeight()    // access method to set Height
   {  return Height;  }

   int getVolume()
   {
      return Length * Width * Height;
   }
}

Why data hiding?  Why should all access to class variables be performed through methods?  It provides an interface for any changes to variables.  This interface (access method) allows for the implementation of data validation, logging, and prevents accidental modification of the variables from the main program.


8.4 Static Variables

In a class definition, variables that are preceded by the keyword "static" become a shared variable among all instances of the class.  That is, each class member addresses the same variable instead of having their own value for the variable.

Below is a program to demonstrate use of a static variable.  Each instance of the Player class (A, B, and C) have their own Name variable.  However, there is only one NumberOfPlayers variable since it is static.  If Player A changes the value of a static variable, then Player B sees the new value.

Static Variables
public class game
{
   public static void main(String[] args)
   {
      Player A = new Player("Luke");
      Player B = new Player("Rey");
      Player C = new Player("Poe");

      System.out.println("Name = " + A.Name + " Number Of Players = " + A.NumberOfPlayers);
      System.out.println("Name = " + B.Name + " Number Of Players = " + B.NumberOfPlayers);
      System.out.println("Name = " + C.Name + " Number Of Players = " + C.NumberOfPlayers);
   }
}

class Player
{
   int Health = 100;
   String Name;
   static int NumberOfPlayers;

   Player(String newName)
   {
      Name = newName;
      NumberOfPlayers++;
   }
}
Output
Name = Luke  Number Of Players = 3
Name = Rey  Number Of Players = 3
Name = Poe  Number Of Players = 3