Document Sample
Classes Powered By Docstoc
					                       Writing Classes
• You have already used classes
   – String, Random, DecimalFormat, JOptionPane, Math, etc
   – To use a class:
       • import the class or the package containing the class
       • create a variable of that type (in most cases, you don’t have to do this for Math
         or JOptionPane)
       • instantiate the variable using new
       • interact with it by passing messages
• We now turn to developing our own classes
   – One aspect of OOP is that any new class expands the language
       • you may use your own classes or others’ classes in building new classes
       • thus, the language continues to grow
   – Another use of the class is for modeling the “real-world” closer
       • a class represents a class of object in the world that we might want to interact
       • each class is self-contained
              Writing and Using Classes
           class named Foo
                                                   Program that
            Data instances:
                                                 uses the class Foo
                                                Foo o = new Foo( );
                                                     o.m1( );
                                                     o.m2( );
You define the a Class as:       You (or others) write a program that uses the
methods (chunks of code          Class by creating one or more instances of the
activated by messages) and       Class as individual objects. These instances are
internal data (data instances)   used by passing them messages, the messages are
that describe the object         the names of the object’s methods, and those
                                 methods manipulate the object’s data
                      Defining a Class
• Before now, we just used pre-defined classes, now we
  will define our own classes
   – They will have methods and instance data
   – They will NOT have a main method
   – They will have a constructor method
      • this method is invoked when the object is first instantiated with “new”
        so any initial things that the object should have or do are performed in
        this method
   – Like our previous programs, a class is stored in a file of the
     same name
      • if the class is Foo, it is stored in the file
   – Before writing your class, you should consider:
      • what data does it need?
      • what methods are required
      • which of the methods should be available to other programs? are any
        of the methods used only internally?
                         Example: Die Class
                                                // import Die; -- in JCreator, don’t import your own
import java.util.Random;                        // classes, just leave them in the same directory as
public class Die                                // this class
{                                               public class DiceStats
   private int numSides;                        {
   private int value;                               public static void main(String[] args)
   private Random generator;                         {
                                                              Die die1, die2;
   public Die(int size) { // constructor                      int i, roll;
      value = 0;
      generator = new Random( );                           die1 = new Die(6);
      numSides = size;}                                    die2 = new Die(6);

   public int getValue() // used to return                 for(i=0;i<50;i++)
   { return value; }     // the die’s value                {
                                                                 die1.rollDie( );
   public void rollDie()                                         die2.rollDie( );
   {                                                             roll = die1.getValue( )
       value = Math.abs(generator.nextInt( ))                          + die2.getValue( );
            % numSides + 1;                                      System.out.println("Roll is " + roll);
    }                                                      }
} // assume this file is called            }
                Some Observations
• We could have made the Die class differently
   – Since generator is only referenced in rollDie, it could have
     been a local variable instead of an instance data
      • But if we had done this, because of how Random works, we might have
        always generated the same die roll!
   – rollDie could have returned the new value
      • so that we would not need getValue, or at least so that we could have
        cut down on the statements in the DieStats class
   – We could also provide a second constructor that receives no
      • such a Die would default to a 6-sided Die
             public Die( )
                                                    Having 2 constructors
                numSides = 6;
                                                    overloads the constructor
                value = 0;
                                                    just as we could overload
                generator = new Random( );
                                                    other methods
      Public, Private and Protected
• These are visibility modifiers
   – Should a class item be accessible outside of the class?
      • If public, then the item can be used directly by anyone
      • If private, then the item can only be referenced inside the class
      • If protected, then the item can only be referenced inside the class, or
        by classes inside the same package (file) or by those child classes
        created using the extends reserved word (recall “extends JPanel)
   – Usually class variables will only be private
   – Methods will usually be public unless they are only used by
     methods of the given class in which case they should be
      • There are occasions for having private methods but there are no
        reason for having public instance data
      • If your class has constants, they are usually public though since no
        one can change them no matter what (since they are constants)
                   The static Modifier
• static can be applied to a method or variable is static
   – It determines whether the item (method/variable) is shared
     among all objects of the class or if it is specific to an object
       • For instance, in our Die class, if we have two Die, d1 and d2, they both
         have their own instance data value
       • If we had made value static, then both d1 and d2 would share value and
         so if we did d1.rollDie( ) it would affect d2
   – We generally do not make instance data static, but we could
     make methods static
       • This is the case in a class like Math or JOptionPane
       • In such a situation, you pass your message directly to the class by name,
         not to an object
           – so we do Math.abs or JOptionPane.showInputDialog(…)
                   Example: Date Class
• The Date class will store a Date’s information:
    – Month
    – Date
    – Year
         • All will be int values as in 6 / 22 / 2004
    – What constructors should it have?
         • Let’s provide one that receives the three values as int parameters, one
           that receives no values (we will then set the date to today, assuming
           today is 6/22/2004) and one that receives the date as a String written
           as “##/##/##”
public class Date                              public Date(int a, int b, int c)
{                                              {
  private int month, date, year;                    month = a; date = b; year = c;
   public Date( )
   {                                           public Date(String x)
      month = 6; date = 22; year = 2004;       {…}        // see next slide
                     Date Class Continued
                                                               public void advanceDate( )
public Date(String x)                                          {
{                                                                 date++;
    String s1 = x.substring(0, 2);                                if(date > 28 && month = = 2)
    String s2 = x.substring(3, 5);                                {
    String s3 = x.substring(6, 8);                                   month++; date = 1;
    month = Integer.parseInt(s1);                                  }
    date = Integer.parseInt(s2);                                  else if (date > 30 && month = = 4 | |
    year = 2000 + Integer.parseInt(s3);                                   month = = 6 | | month = = 9 | |
}                                                                         month = = 11)
                                                                          month++; date = 1;
public void setDate(int newMonth, int newDate, int newYear)        }
{                                                                  else if (date > 31)
     month = newMonth;                                             {
     date = newDate;                                                      month++; date = 1;
     year = newYear;                                                      if (month = = 13)
}                                                                         {
                                                                              month = 1; year++;
public void getDate( )                                                    }
{                                                                  }
     System.out.println(month + "/" + date + "/" + year);     }
           Class Methods:
  Mutators, Accessors, Constructors
• We have already mentioned Constructors
   – Methods that initialize an object
   – All classes must have at least a constructor (although if you
     forget to provide one, Java gives you a default constructor that
     doesn’t do much)
• In addition, a class will require methods to
   – Access a data member to return the value so that it can be used
     elsewhere (known as accessor methods)
   – Allow values stored in data members to be updated/altered
     (known as mutator methods)
      • In the Date example, setDate and advanceDate are mutators,
        and getDate is an accessor
           BaseballPlayer                               public void playsGame(int a, int s, int d, int t, int h)

            Class Code                                       atBats+=a;
public class BaseballPlayer                                  triples+=t;
{                                                            homers+=h;
   private String name, position, team;                      update( );
   private int atBats, hits, doubles, triples, homers; }
   private double battingAvg, sluggingPct;
                                                       public void oneBat(int result) {
  public BaseballPlayer(String n)                           atBats++;
  {                                                        switch(result) {
           name=n;                                                 case 1 : hits++; break;
           position=null; team=null;                               case 2 : doubles++; break;
           atBats=0; hits=0; doubles=0; triples=0;                 case 3 : triples++; break;
           homers=0;                                               case 4 : homers++; break;
  }                                                        }
                                                           update( );
   public BaseballPlayer(String n, String p, String t) }
           name=n;position=p;team=t;                   public void update( ) {
           atBats=0; hits=0; doubles=0; triples=0;          battingAvg=(double)(hits+doubles+triples+
           homers=0;                                               homers)/atBats;
   }                                                         sluggingPct=(double)(hits+doubles*2+
      Baseball Player Code Continued
                                                     public class BaseballGame
public double getAvg( )                               {
{                                                        public static void main(String[ ] args)
    return battingAvg;                                   {
}                                                                BaseballPlayer b1, b2, b3;
                                                                 b1=new BaseballPlayer(…);
public double getSlugging( )                                     b2=new BaseballPlayer(…);
{                                                                b3=new BaseballPlayer(…);
     return sluggingPct;                                         b1.playsGame(5, 2, 1, 0, 0);
}                                                                b2.playsGame(4, 3, 0, 0, 0);
public void traded(String newTeam)                               b3.oneBat(2);
{                                                                System.out.println(b3);
     team=newTeam;                                               b3.traded(“Cardinals”);
}                                                                b2.traded(“Reds”);
public String toString( )                                        System.out.println(b1.getAvg( ));
{                                                        }
      return name + “\n” + position + “\n”           }
            + team + “\n” + “bats: ” + battingAvg;
             The toString( ) Method
• What is the toString method? Imagine that we did
  not have one and we did
   – System.out.println(b1);
• What would you get?
   – All objects are stored in memory and pointed to by things called
     reference variables, or pointers
   – If you try to print out a reference variable, you get the value of the
     address in memory of the actual object, not the object’s value(s)
• The role of toString is to provide the programmer
  with a way to return a String that describes the
  contents of an object so that it can be printed out
   – Its up to us as programmers to decide what to print out in
     the toString, for the BaseballPlayer, we did not print out
     all of the information, but we could have
  Programming Process with Classes
• If you write a class that you plan to use in another class, you
  must first compile the class to be used
   – this class will not have a main method, so it can not be run directly
• Once compiled, you use it in another class (much as you have
  used String or Random)
   – declare a variable to be of the class type (e.g., Die d1;)
   – instantiate the variable (e.g., d1 = new Die(8);)
   – pass the variable messages (d1.rollDie( );)
       • NOTE: in JCreator, the compiled class must be in the same directory as the
         class that will use it, otherwise you will have to use an import statement
       • for simplicity, we will just make sure all of our classes are in the same
• You must make sure that your class did compile (no syntax
  errors) before you can try to test it out – don’t just assume it
   – unfortunately, testing the compiled class means writing a second “user”
     class to test it from – this can be awkward when it comes to debugging
     complex code
              What Does new Do?
• The reserved word new plays the role of
  instantiating an object
  – This causes the operating system to provide the
    memory space needed for the object
  – And initializes the object as needed
     • Many classes require parameters to initialize their object,
       we will see some examples as we go through this section
• Once done, you can now interact with the object
  by passing the object messages
  – However, if you try to pass a message to an object
    that is declared but not instantiated, you will receive a
                         The this Reference
• this is a reference to this object
• We can use this if code inside the object must refer to the
  object itself
      – The simplest example occurs in a constructor where we want to
        reference this object’s instance data rather than a parameter
  public class ThisExample
     private int x;
                                     By using this.x, the Java compiler knows that the left-
     private int y;
                                     hand variable is the instance data x in the class and the
                                     right-hand variable is the parameter
      public ThisExample(int x, int y)
             this.x = x;                     We will use the this reference when we want
             this.y = y;                     to refer to this object as handling some kind
       }                                     of activity like being an Event handler
     … // rest of class defined here         (something you will see later this week)

Shared By: