| For the physicist one of the obvious examples that 
              comes to mind when considering a good subject for object representation 
              is a particle. A particle is a self contained physical object 
              with well defined attributes and behavior. We might provide a class for fundamental particles 
              such as an electron, quarks and photons, or composite particles 
              such as protons, atoms, and molecules. Below we show a class that holds the essential properties 
              of a stable particle. We will show in later chapters how this class 
              could be extended 
              by sub-classes to include additional properties such as lepton number, 
              quark content, half-life for unstable particles, etc.  We also do not include kinematic information, such 
              as the particle's momentum or kinetic energy. That depends on the 
              frame of reference and this class only deals with the internal state 
              properties of a particle at rest. We will show later how an interface 
              can add such kinematical values. 
              
                 
                  | Particle.java |   
                  | // A base class for particles.
public class Particle
{
  // Instance variables
  String name;  // e.g. electron, proton, etc.
  double mass;  // rest mass in MeV/c^2int charge;   // integer charge only (ignore quarks)
 int  spin;    // multiple of 1/2
  // Constructor
  public Particle(String name, double mass,
                  int charge, int spin)
  {
    this.name = name;
    this.mass = mass;
 this.charge = charge;
 this.spin = spin;
  }
  public String getName()
  {
    return name;
  }
  public double getMass()
  {
    return mass;
  }
  public int getCharge()
  {
    return charge;
  }
  public int getSpin()
  {
 return spin;
  }
}
 |  
                Note: The 
                  get*() 
                  type of method has become the convention for accessing the properties 
                  of an object. So-called getter methods that return 
                  the values of particular property values while, setter 
                  methods (such as setX(double 
                  x) ) set a property variable to a particular value.  
Furthermore, special classes called Java Beans 
                require the use of such names so that bean tools can automatically 
                recognize the function of a particular method. We can then use the above class as follows:   Particle 
              [] particles = new Particle[4];
 particle[0] = new Particle("electron", 0.511, 
              -1, 1);
 particle[1] = new Particle("positron", 0.511, 
               1, 1);
 particle[2] = new Particle("proton",   938.0, 
               1, 1);
 particle[3] = new Particle("neutron",  940.0, 
               0, 1);
 
 to define an array of four different types of particles.   Latest update: Dec.15.2003 |