Object-oriented Programming - The Object-oriented Programming Paradigm.ppt

Document Sample
Object-oriented Programming - The Object-oriented Programming Paradigm.ppt Powered By Docstoc
					The Object-oriented Programming
The Software Crises (1980’s)

 •Software is a handcrafted, customized product  scarce, expensive

 •Hardware is built from standardized, “off the shelf” components that
 can be easily replaced and upgraded  plentiful, cheap

  •Can software be produced in sufficient quantity to meet the rapidly
  growing demand generated by the availability of cheap hardware?

  •How can one make software more like hardware?

 The object-oriented paradigm is a methodology for producing
 reusable software components
 The Object-oriented Programming Paradigm

The Software Lifecycle
                        Any large system that requires a year
 •Requirements Document
                               Identify the objects in the
                               Write a thorough
                              In the object-oriented paradigm,
                             Developthe code to implement
                        or two to develop new, will likely be
                              the individual a the “problem
                               problem domainwell their
                               the design. In and
                             understanding components
                        around for decades.ofWhile
                               associations. Construct models
                               engineered tested before they
                              (classes) are project, this should
                             domain” through discussions
 •Analysis / Design     maintenance does include “correctrive
                              arethe shortest domain to
                               be the customer culminating
                               of included into the system.
                             withthe problem and most
                        maintenance”, those problems should
                               mechanical the interaction
                               understand phase of the
                              Good programming discipline
                             in a document exhaustively
 •Implementation        be largely eliminated after testing.
                               between the the programmer
                              also requires various objects. to
                        The documenting the requirements
                             bulk of the maintenance effort
                              identify pre andyou will
                               During design, post conditions
                             of can amount be built. add
                        (whichthe system toto 80-90% of the
  •Testing                     “solution domain” to ensure
                              and loop invariants concepts
                        total programming effort that is
                               such as structures code for each
                              “provably correct” for holding
                        devoted to the project) is involved in
                               data to the
                              component. analysis models.
  •Maintenance          updating and enhancing the original
                        product. The programmers doing the
                        maintenance will rarely be the same
                        people who were involved in the initial
The Object-oriented Programming Paradigm

 Features of OOP

  A software system is a collection of collaborating objects

     •Objects consist of attributes (data) and behaviors
     •Objects collaborate to provide functionality by
     exchanging messages

 Objects are dynamically created at run-time. The programmer
 designs and implements a class which is a “factory template”
 for creating objects. Objects are instances of a class
  The Object-oriented Programming Paradigm


   Student is a class with

          Attributes: name, socialSecurityNumber, credits, major,
          gpa, coursesCompleted, courseSchedule

       Methods: addCourse(), dropCourse(), changeMajor(),
       completeCourse(), findAve(), showGPA(), printCourseList()

  All students have these attributes and can execute these
  The Object-oriented Programming Paradigm

Sue Smith, Tom Jones, and Mary Bell are three Student objects.

  •They each maintain their own separate data (values of the attributes)

   •They can receive messages to implement any of the methods of the
   •When new students enroll, new Student objects will be created

    • When these students graduate, their records can be archived and the
    objects deleted.
The Object-oriented Programming Paradigm

Objects have the following properties:

•Strong encapsulation

•Provide for inheritance

•(sub) Systems may be created by a composition of objects

•Polymorphism promotes reusability of code and provides
late (run-time) binding

•Container objects can be generic – hold any of a variety of objects.
 The Object-oriented Programming Paradigm
                                  class combines private data attributes with
•Strong encapsulation             (public) methods that operate on this data

  public class WaterTank {
      private static final double capacity = 500; //gallons
      private double contents; // gallons
      public WaterTank ( ) {..} //constructor
      public void addWater (double amt) {..} // transformations
      public void removeWater (double amt) {..}
      public boolean IsFull( ) {..} // observations
      public boolean IsEmpty( ) {..}
      public double showContents( ) {..}
          Only ability that a client (user of this class) has to view or
          change data is through the methods that are provided.
        The Object-oriented Programming Paradigm

                  Base class                                Derived class

                Class Name                                   Class Name
        attributes                                     Additional attributes
        (data and object refs.)                        (if any)
        Behaviors                                     Additional methods or
        (methods)                                     overrrides

    public class BaseClassName {   public class DerivedName extends BaseClassName{
       //private attributes
                                       //inherits all of the attributes from base class
       //public methods
                                       //may add attributes of its own
                                       //constructor(s) for derived class
                                       //may add methods or override method in base
      The Object-oriented Programming Paradigm

     The header for a derived class has the following form:

      public       class     ClassName         extends        BaseClassName {

      The constructor in a derived class must pass any necessary
                   type – Indicates inheritance – constructor.
      visibility modifier indicates the location, amount, and
      initialization parameters to the base class may inherit
                           from only one class
                   organization of memory to be allocated
            Suppose we have the following base class:
       Ex. derived class has the following constructor:
                                     public class Derived extends Base {
 public class Base {
                                       private int derivedInt;      Additional attrib.
     private String name;
                                       public Derived(String s1, int x) {
     public Base(String nmStr) {               super(s1);         Must be first stmt. in
           name = new String(nmStr);           derivedInt = x;    constructor

     }                                  }
                                        //any additional methods or overrides
     //other methods
       The Object-oriented Programming Paradigm

      Consider a class Animal:

              private String name;
              private String says;
              public Animal(String str, String s2){   Constructor
                 name = new String(str);
                 says = new String(s2);

              public void speak( ) {                  Behavior
         The Object-oriented Programming Paradigm
        Animal serves as the base class for several derived classes
public class Dog extends Animal {                  public class Bird extends Animal {
    public Dog(String says ) {                         public Bird(String says) {
          super(“Dog”, says);                              super(“Bird”,says);
    }                                                  }
    public void move ( ) {                             public void move ( ) {
          System.out.println(“ -- I run”);                 System.out.println(“ -- I fly”);
    }                                                  }
                        Initialize base class attributes

               New methods can extend the behavior of the base class
      The Object-oriented Programming Paradigm

                                     Animal                            Base class
                             String name;
                             String says;

                             public Animal(String, String)
                             public void speak( )

                                                                           Derived classes
                                                                           extend the base class

                 Dog                                                   Bird
       public Dog(String)                                    public Bird(String)
       public void move( )                                   public void move( )
         The Object-oriented Programming Paradigm
    Consider the following application (class AnimalHouse)
  public class AnimalHouse {                       public static void main(String [ ] args) {
     private Dog Lassie;                                 AnimalHouse zoo = new AnimalHouse( );
     private Bird TweetyBird;                            zoo.animalAct( );
     private Animal Felix;                         }
     public AnimalHouse ( ) {                      }//end class AnimalHouse
             Lassie = new Dog(“ -- bow-wow”);
             TweetyBird = new Bird(“ -- tweet-tweet”);
             Felix = new Animal(“Cat”, “ -- meow”);                    Output
                                                           The class contains three
                                                           The constructor allocates
                                                         The application class
     }                                                     attributes (“data” members)
                                                           memory for the three private
                                                         (AnimalHouse) contains a main
     public void animalAct( ) {                             Dog -- objects of the
                                                           that areand initializes their
                                                           objects that creates an base
             Lassie.speak( );                              class Animal, or one of the
                                                         instance of the class and tells
                                                            Bird -- tweet-tweet
             TweetyBird.speak( );                          classes derived from it.
                                                         the AnimalHouse object zoo to
             Felix.speak( );                                Cat -- meow
                                                         execute its animalAct( )
             Lassie.move( );
                                                             -- I run
             TweetyBird.move( );
     }                                                       -- I fly
          Felix cannot receive a message move( )
     The Object-oriented Programming Paradigm

    Consider the class Counter described below

      public class Counter {
          private int count, base;
          public Counter(int baseVal) {…}
          public void increment( ) {…}
          public void reset( ) {…}
          public int viewCount( ) {…}

    We may use composition to build a Clock out of Counter objects
    The Object-oriented Programming Paradigm

    public class Clock {
                                                 These Counter objects are not
       private Counter hours, mins, secs;
                                                 accessible outside of a Clock object.
       public Clock( )
              hours = new Counter(24);
              mins = new Counter(60);             Each Clock object must hold
              secs = new Counter(60);
                                                  its own set of Counter objects
       public void tick( ) {                       Clock methods are
              secs.increment( );                   implemented by the Counter
              if (secs.viewCount( ) == 0) {        components
                   mins.increment( );
                   if((secs.viewCount( )==0) && (mins.viewCount( ) == 0))
                         hours.increment( );
       }                  In an assignment you will add methods set( ) and
    }                     viewHr(), viewMin( ), and viewSec( ) to this class
        The Object-oriented Programming Paradigm
   Suppose we want to construct a new class called AlarmClock that has
   all of the features of a Clock, but adds an alarm as well.
   public class AlarmClock extends Clock {          Inherits from class Clock
      private boolean alarmOn;
                                              Additional attributes in an AlarmClock
      private int hrSet, minSet;
      public AlarmClock( ) {alarmOn = false;} //the alarm is not set initially
      public void setAlarm(int hr, int min) {               Additional methods in AlarmClock
             hrSet = hr; minSet = min; alarmOn = true;
      public void tick( ) {      Override the implementation of tick( ) in parent
             super.tick( );         Execute the version of this method in the parent class
             if ((viewHr( ) == hrSet)&&(viewMin() == minSet)&&alarmOn){
                       System.out.println(“ring, ring, ring”);
      }                                                          viewHr() and viewMin( )
                                                                 are methods in an
      public void resetAlarm( ) {alarmOn = false;}               AlarmClock that are
   }                                                             inherited from its parent
     The Object-oriented Programming Paradigm

   The constructor AlarmClock( ) initializes the boolean variable
   alarmOn to false, and leaves the initial alarm settings at the default
   values – hrSet = 0 and minSet = 0. The constructor for the base class
   does not take any parameters, and no additional initialization is
   needed to instantiate the three Counter objects.

   The method tick( ) is overriden in the derived class. After every tick
   of the clock, a test is done to see whether it is time for the alarm to go
   off. The methods viewHr( ) and viewMin( ) are inherited from the
   base class and are available to any client of an AlarmClock object
   (including the methods of this class).
     The Object-oriented Programming Paradigm
Polymorphism and Genericity

     These two topics will be studied in depth in CS2.
          The only container object we have studied so far is the array. Arrays of
          any type can be declared, and the array operations such as
          •Assignment        ex. A[0] =    assigned value of the declared type.
          •Retrieval         ex. Itemtype myVar = A[3]; //retrieve object at index 3
          •Length            A.length
          are syntactically independent of the type being stored in the array.

          We will have a need to construct (or use) various other container
          classes; and objects of container classes should be capable of
          holding any kind of object and provide the same functionality to
          the user regardless of their contents.
   The Object-oriented Programming Paradigm

    There are a variety of forms that polymorphism may take:

    1. Overloading of function names.

       functions with different parameter lists may have the same identifier
          Ex:      public static int sqr(int x) {…}
                   public static double sqr(double x) {..}
          The compiler determines which function to use by the type of the argument in
          the function call.
        An operation in a base class may be overridden in a derived class.
          Ex:       function tick( ) is redefined in AlarmClock
     2. Overloading of operators
         The operator + can be used to add pairs of any of the primitive types
         and to concatenate Strings. However, Java does not permit the
         programmer to define additional operations for any operator.
         The Object-oriented Programming Paradigm

        3. Polymorphic variables

              Run-time binding of a method call to a recipient object.
                Consider the following application
public class Example {
    private Dog fido;
    private Bird robin;
    public static void main(String [ ] args) {
           fido = new Dog( “ -- ruff-ruff”);                 Make Animal reference to a
           robin = new Bird( “ -- tweet-tweet”);             derived class object
           Animal critter;
           critter = fido;
           critter.speak( );                       Dog – ruff-ruff       Executes method
                                                                         speak( ) for a derived
           critter = robin;                                              class object.
           critter.speak( );                       Bird – tweet-tweet
       The Object-oriented Programming Paradigm
                critter.speak( ); Bird(“ tweet-tweet”);
                 critter = =critter; ruff-ruff”); tweet-tweet
 Polymorphism      fido = new
                  tweety new );
                critter = tweety;

  critter           fido               critter             tweety

                  Dog                                      Bird

                  ruff-ruff                               tweet-tweet

ruff-ruff                          Animal base
                speak( )           class features       speak( )

                move( )            Not accessible       move( )
                                   by messages to
      The Object-oriented Programming Paradigm

    In the previous example, an Animal object reference (critter) could
    attach to objects of the derived classes Dog and Bird and send
    messages to any of the methods that were common with (have the
    same interface – identifier, parameters, and return type) methods in
    the base class.

    Note! Casting could be used to be able to send messages to any of the
    derived class methods.

     (Bird)critter.move( );   //to obtain -- I fly
       The Object-oriented Programming Paradigm

  1.     The object-oriented paradigm is a programming methodology that
         promotes the efficient design and development of software systems
         using reusable components that can be quickly and safely assembled
         into larger systems.
  2.     The basic unit of code is the class which is a template for creating run-
         time objects.
  3.     A class encapsulates data (primitive types and object references) and
         the operations that can be performed on this data.
  4.     The modifiers public, private, and protected (accessible to derived
         classes, but not to any other) limit and control the access that client
         code has to the attributes (data) of a class. Provides for security.
  5.     Classes can be composed from other classes. For example, Clocks can
         be constructed as an aggregate of Counters.
       The Object-oriented Programming Paradigm
Review (cont.)

      6.   Inheritance provides a means of easily implementing the “is a”
           association between classes of objects. A dog “is a(n)” Animal with
           additional attributes and behaviors unique to dogs.
      7.   Much of the power of inheritance derives from the late (run-time) binding
           feature of an object-oriented language. We may have a container of
           Shapes where the individual Shape objects are instances of derived
           classes such as Circle, Square, Rectangle, and Triangle. A reference to a
           Shape, will be to one of these derived objects, and a message for the
           Shape object to calculate its area will be received by the area( ) method of
           the particular derived class object.
      8.   For container classes to be generally reusable, they must be generic – able
           to hold almost any kind of primitive type or object.
      9.   Java provides automatic garbage collection, relieving the programmer of
           the need to ensure that unreferenced memory is regularly deallocated.

suchufp suchufp http://