Docstoc

Object-Oriented Design and Programming

Document Sample
Object-Oriented Design and Programming Powered By Docstoc
					 Objects and Classes




Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   1
Recap
A Java application is a set of
 cooperating classes




          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   2
Recap: Objects

 Objects (instances) can be
  created from classes
 Objects have methods that can
  be invoked
 Objects have a state (they hold
  data)
 Objects can create other objects
        Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   3
Learning about objects
Select an object, as in the lecture last
 week
Describe the object in English
Find generic names for any items on the
 list
Can you categorise the items on the list?




            Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   4
  Objects

Objects have properties that

  describe attributes (or states) of the object

  describe the actions the object can perform




             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   5
Classes of objects

 A class is a type or kind of object.
 All objects in the same class have the same
  attributes (data and methods)
 Each individual object is a member of the
  class.
 Each individual object is an instance of the
  class.



            Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   6
Recap: Classes

Classes define what objects look
 like: they define the methods and
 the data fields (attributes)
Classes are defined by Java
 source code
“Programming” is writing class
 definitions
         Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   7
 Software objects

    A pictorial view of the class specification of Person



Name of class
                                Person                        attributes
                             name

                              age

                            gender



                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.      8
Anatomy of a class

   class class-name
   {
        fields (instance data)

        constructor(s)

        methods
   }
         Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   9
A class      class Timer
             {
                      private int hours;
                      private int minutes;
                      private int seconds;

                        /**
                         * Construct a timer object initialised to 0:00:00
                         */
                        public Timer()
                        {
                                 hours = 0;
                                 minutes = 0;
                                 seconds = 0;
                        }

                        /**
                         * Return the current time of this timer.
                         */
                        public String getTime()
                        {
                                  return hours + “:” +
                                           minutes + “:” +
                                           seconds;
                        }
            }
          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.         10
The class name

class Timer                                 convention: class names
{
     ...                                    start with uppercase letter
}

      The class name is an identifier.

 A Java identifier must
 • contain only letters, digits, underscore (_) and dollar
    sign ($)
 • not start with a digit
              Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   11
The class Person


                        Person
       surname
       forename
       age
       gender




       Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   12
Identifiers


  valid:                              invalid:

  number                              number of points
  x98                                 99x
  howMany                             birth.year
  NUMBER_OF_POINTS                    ARRAY-SIZE
  $yes$
  _$$S_$_



           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   13
Fields

             private int hours;
             private int minutes;
             private int seconds;

                                                                an identifier
   field declaration:
           access-modifier type name;

   “private” for fields
                                         the type of value that
                                         this field can hold

                                               convention: field names
                                               start with lowercase letter
                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.           14
Field naming

  fields should have meaningful names
  - convention: start with lower case
  good:
          yearOfBirth
          numberOfSeats
          totalTime
  bad:
          yb
          s
          number

             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   15
Fields: an example

  object of class timer:




                    hours
               minutes
               seconds




             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   16
An instance of the Person
class

                       The object person_1

 Name of object
                             person_1

                      name
                                                                Values of
 attributes                                                     attributes
 (instance            age
 variables)
                      gender



              Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.          17
Creating objects / instances
class Line
{
  private Point start;
  private Point end;

    public Line(int x1, int y1, int x2, int y2)
    {
      start = new Point(x1, y1);
     end = new Point(x2, y2);
    }
    ...
}
             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   18
Creating objects: syntax



      syntax:

       new className(parameters)




        Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   19
Another example
class Person
{
   private String fullName;
   private Address address;
   ...
   public Person(String name, String street,
                  String city)
   {
       fullName = name;
       address = new Address(street, city);
   }
}
           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   20
Creating objects (constructor)

 We have to create objects before we
  can use them.
 Look at the two statements below.
  What is the difference?

 Person person1;

 Person person1 = new Person( );

          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   21
Software engineering
approach
Classes as modules
  Encapsulation
    all data and actions are collected together into a
     single module
  Information hiding
    the details of the implementation (both internal
     data and how the methods work) are hidden from
     the user




              Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   22
Data for objects of Person class
Each object has a number of data items
 (instance variables) that hold information about
 attributes of that particular object. They are
 usually private to the class.
For the class Person, the instance variables are :
  forename, surname, age, gender
As code in the class they appear as:
  private   String forename;
  private   String surname;
  private   int age;
  private   int gender;
                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   23
Constants of the class Person




             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   24
Class specification of Person with
attributes hidden from the user -
information hiding,
encapsulation
                             Person

                         name

                         age

                        gender



         Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   25
methods are needed to access the
“hidden” attributes of Person - the
class must contain the description of
these methods
                                Person
                                             getName()
                        name
                                             setName()
                                              getAge()
                        age
                                              setAge()
                                            getGender()
                       gender
                                            setGender()


          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   26
Requesting an object to carry
out an operation
Operations are carried out by issuing a request to
 an object
This is done by calling a method - tell me your
 name
The object uses data from
  the internal information that represents the state of
   the object (the value of the object’s instance
   variables)
  any data provided along with the request (the
   arguments or parameters of the method)

             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   27
Recap: Methods

An object can call a method of
 another object
Methods do something: they
 change the state of the object or
 return some information
Methods can have parameters
Parameters have types
          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   28
Setting the attributes of person_1



  person_1 is an object (instance) of Person class -
  How do we set the name, age, gender, etc?

                 person_1
              name          “Fred Smith”               “Fred Smith”

                age                 20                         20

              gender               male                      male



             Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.    29
Setting the attributes of object person_1
(an instance) using the methods



               person_1
     name                         getName()
        “Fred Smith”                                       “Fred Smith”
                                  setName()
     age       20                  getAge()                       20
                                   setAge()
      gender                    getGender()
               male                                              male
                                 setGender()


               Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.      30
Requesting the setting of someone’s age

                     bill             setAge()          25


              bill

   name                          getName()
          “Bill Bloggs”
                                 setName()
   age         25                 getAge()                       25
                                  setAge()
   gender
              male             getGender()
                                setGender()


              Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   31
Requesting a Person object to tell its gender


               female                 jean               getGender()


                jean
      name                        getName()
         “Jean Jones”
                                  setName()
     age        38                 getAge()
                                   setAge()
      gender                    getGender()                    female
               female
                                 setGender()


               Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.    32
Java program that uses the Person
class
 /** A comment usually goes here about the program or class*/
 import java.io.* ;
 public class CreatePersons
 {
   /** a comment about the method goes here*/
   public static void main(String[] args)
      {
     // instructions for the method go in here
    // for example
    // step 1 - declare two "Person" variables
      Person person1 = new Person() ;
      Person person2 = new Person(“Stephanie”, 9, “female”) ;
    // the rest of the instructions go here
    } // end of method main
 } // end of class CreatePersons
               Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   33
Methods                           /**
                                   * Return the current time of this timer.
                                   */
                                  public String getTime()
    a natural language            {
    comment explaining                    return hours + “:” +
    what this method does                         minutes + “:” +
                                                  seconds;
 /**                              }

  * method comment                the type of value that
  */                              this method returns

 access-modifier return-type name (parameters)
 {
       body
               “public” for most methods        an identifier
 }

                  implementation                 convention: method
                  of method                      names start with
                                                 lowercase letter
                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.         34
Methods: an example

  object of class timer:




                                                      getTime()

                        “getTime()”

                                              “12:45:07”


          Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   35
Methods

                              signature - convention: start
                              with lower case
 public String getTime()
 {
         return hours + “:” +
                  minutes + “:” +
                  seconds;
 }


                                     body



                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   36
Method categories


    constructor
    accessor / selector (get)
    mutator (set)

 Each method should be in one (and only one)
 category.



           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   37
Constructors



  A constructor constructs and initialises
  the object.




           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   38
Constructors
 class Timer
 {                                               A constructor is a special
    ...                                          methods that is executed when
     /**                                         an object is created.
      * Construct a timer object
      * initialised to 0:00:00
      */                                         The name of the constructor
     public Timer()                              method is the same as the name
     {                                           of the class.
              hours = 0;
              minutes = 0;
              seconds = 0;                       A constructor has no return type.
     }
     ...
 }                                               The purpose of the constructor is
                                                 to initialise the object to a valid
                                                 state.


                      Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.        39
Mutators

  Also known as "set method”.


  A mutator changes the state of an
  object.




           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   40
Setting instance (object) variables’
values
  public static void main(String[ ] args)
    {
    // step 1 - declare two "Person" variables
    Person person1 = new Person() ;
    Person person2 = new Person() ;

    // step 2 - set the attributes of "person1"
    person1.setForename("John") ;
    person1.setSurname("Smith") ;
    person1.setAge(24) ;

    // step 3 - set the attributes of "person2"
    person2.setForename("Peter") ;
    person2.setSurname("Wright") ;
    person2.setAge(19) ;
               Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   41
Setting an attribute of an object




/**
   * set the forename attribute of the person
   * @param f the forename of the person
*/
public void setForename(String f) {
  if (f.length() < 1)
  {
     System.err.println("bad forename argument in
   'setForename'") ;
     System.exit(1) ;
  }
  forename = f ;
} // end of method setForename
                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   42
Accessors

  Also known as "selector”, “get
  method”.

  An accessor provides access to one bit
  of information about the object. It does
  not change the object.




           Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   43
Getting instance variables’ values
 // step 4 - display the attributes of "person2"
    System.out.print("the second person is ") ;
    System.out.print(person2.getForename()) ;
    System.out.print(" ") ;
    System.out.print(person2.getSurname()) ;
    System.out.println(“(“ + person2.getAge() + “)”) ;
         System.out.println() ; // step 5 - leave a blank line
 // step 6 - display the attributes of "person1"
    System.out.print("the first person is ") ;
    System.out.print(person1.getForename()) ;
    System.out.print(" ") ;
    System.out.print(person1.getSurname()) ;
    System.out.println(“(“ + person1.getAge() + “)”) ;
 } // end of method main


                Copyright@ M Kölling, A Ellis, L Seldon, Monash Univ.   44

				
DOCUMENT INFO