1 / 24

The Object-oriented Programming Paradigm

The Object-oriented Programming Paradigm. 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.

braden
Download Presentation

The Object-oriented Programming Paradigm

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Object-oriented Programming Paradigm 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

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

  3. The Object-oriented Programming Paradigm Features of OOP A software system is a collection of collaborating objects • Objects consist of attributes (data) and behaviors(methods) • Objects collaborate to provide functionality by exchanging messages Objects are dynamically created at run-time. The programmer designs and implements a classwhich is a “factory template” for creating objects. Objects are instances of a class

  4. The Object-oriented Programming Paradigm Example 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 methods.

  5. 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 class. • When new students enroll, new Student objects will be created • When these students graduate, their records can be archived and the objects deleted.

  6. The Object-oriented Programming Paradigm Objects have the following properties: • Strongencapsulation • Provide for inheritance • (sub) Systems may be created by a composition of objects • Polymorphism promotes reusability of codeand provides late (run-time) binding • Container objects can be generic – hold any of a variety of objects.

  7. class combines private data attributes with (public) methods that operate on this data The Object-oriented Programming Paradigm • Strongencapsulation publicclass WaterTank { privatestaticfinaldouble capacity = 500; //gallons privatedouble contents; // gallons public WaterTank ( ) {..} //constructor publicvoid addWater (double amt) {..} // transformations publicvoid removeWater (double amt) {..} publicboolean IsFull( ) {..} // observations publicboolean IsEmpty( ) {..} publicdouble showContents( ) {..} } Only ability that a client (user of this class) has to view or change data is through the methods that are provided.

  8. Class Name attributes (data and object refs.) Behaviors (methods) The Object-oriented Programming Paradigm Inheritance Derived class Base class Class Name Additional attributes (if any) Additional methods or overrrides publicclass BaseClassName { //private attributes //public methods } publicclass DerivedName extends BaseClassName{ //inherits all of the attributes from base class //may add attributes of its own //constructor(s) for derived class //may add methods or override method in base }

  9. visibility modifier type – indicates the location, amount, and organization of memory to be allocated Indicates inheritance – may inherit from only one class Additional attrib. Must be first stmt. in constructor The Object-oriented Programming Paradigm Inheritance 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 initialization parameters to the base class constructor. Ex. Suppose we have the following base class: The derived class has the following constructor: publicclass Derived extends Base { privateint derivedInt; public Derived(String s1, int x) { super(s1); derivedInt = x; } //any additional methods or overrides } publicclass Base { private String name; public Base(String nmStr) { name = new String(nmStr); } //other methods }

  10. Animal private String name; private String says; The Object-oriented Programming Paradigm Inheritance Consider a class Animal: Attributes Constructor public Animal(String str, String s2){ name = new String(str); says = new String(s2); } Behavior public void speak( ) { System.out.println(name+says); }

  11. The Object-oriented Programming Paradigm Inheritance Animal serves as the base class for several derived classes publicclass Dog extends Animal { public Dog(String says ) { super(“Dog”, says); } publicvoid move ( ) { System.out.println(“ -- I run”); } } publicclass Bird extends Animal { public Bird(String says) { super(“Bird”,says); } publicvoid move ( ) { System.out.println(“ -- I fly”); } Initialize base class attributes New methods can extend the behavior of the base class

  12. Animal String name; String says; public Animal(String, String) publicvoid speak( ) Dog Bird public Dog(String) publicvoid move( ) public Bird(String) public void move( ) The Object-oriented Programming Paradigm Inheritance Base class Derived classes extend the base class

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

  14. The Object-oriented Programming Paradigm Composition Consider the class Counter described below publicclass Counter { privateint count, base; public Counter(int baseVal) {…} publicvoid increment( ) {…} publicvoid reset( ) {…} publicint viewCount( ) {…} } We may use composition to build a Clock out of Counter objects

  15. These Counter objects are not accessible outside of a Clock object. Each Clock object must hold its own set of Counter objects The Object-oriented Programming Paradigm Composition publicclass Clock { private Counter hours, mins, secs; public Clock( ) hours = new Counter(24); mins = new Counter(60); secs = new Counter(60); } publicvoid tick( ) { secs.increment( ); if (secs.viewCount( ) == 0) { mins.increment( ); if((secs.viewCount( )==0) && (mins.viewCount( ) == 0)) hours.increment( ); } } } Clock methods are implemented by the Counter components In an assignment you will add methods set( ) and viewHr(), viewMin( ), and viewSec( ) to this class

  16. Inherits from class Clock Additional attributes in an AlarmClock Override the implementation of tick( ) in parent Execute the version of this method in the parent class The Object-oriented Programming Paradigm Inheritance 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. publicclass AlarmClock extends Clock { privateboolean alarmOn; privateint hrSet, minSet; public AlarmClock( ) {alarmOn = false;} //the alarm is not set initially publicvoid setAlarm(int hr, int min) { hrSet = hr; minSet = min; alarmOn = true; } publicvoid tick( ) { super.tick( ); if ((viewHr( ) == hrSet)&&(viewMin() == minSet)&&alarmOn){ System.out.println(“ring, ring, ring”); } publicvoid resetAlarm( ) {alarmOn = false;} } Additional methods in AlarmClock viewHr() and viewMin( ) are methods in an AlarmClock that are inherited from its parent

  17. The Object-oriented Programming Paradigm Inheritance 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).

  18. The Object-oriented Programming Paradigm Polymorphism and Genericity These two topics will be studied in depth in CS2. Genericity • 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.

  19. The Object-oriented Programming Paradigm Polymorphism 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: publicstaticint sqr(int x) {…} publicstaticdouble 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.

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

  21. fido tweety critter critter Dog Bird ruff-ruff tweet-tweet speak( ) speak( ) move( ) move( ) The Object-oriented Programming Paradigm critter.speak( ); Polymorphism critter = tweety; critter = fido; tweety = new Bird(“ tweet-tweet”); Animal critter; fido = new Dog(“ ruff-ruff”); critter.speak( ); tweet-tweet ruff-ruff Animal base class features Not accessible by messages to critter

  22. The Object-oriented Programming Paradigm Polymorphism 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

  23. The Object-oriented Programming Paradigm Review • 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. • The basic unit of code is the class which is a template for creating run-time objects. • A class encapsulates data (primitive types and object references) and the operations that can be performed on this data. • 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. • Classes can be composed from other classes. For example, Clocks can be constructed as an aggregate of Counters.

  24. The Object-oriented Programming Paradigm Review (cont.) • 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. • 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. • For container classes to be generally reusable, they must be generic – able to hold almost any kind of primitive type or object. • Java provides automatic garbage collection, relieving the programmer of the need to ensure that unreferenced memory is regularly deallocated.

More Related