CPT 4 : Object Oriented Programming (OOP) Object Oriented Programming (OOP) is a type of programming where the programmer defines objects. Each object can store data and defines methods (or procedures) which operate on the data. Usually the data is hidden within the object and can only be accessed by calls made to the object’s methods from other objects. Different objects are required for different types of data, for example a “car” object or a “linked list” object. This is because different data needs to be stored and different operations will be required on different types of data. Objects are often known as classes. Two common OOP languages are C++ and SmallTalk. All OOP languages support these key concepts : Encapsulation, Inheritance and Polymorphism. Advantages of OOP Data stored in an object can only be accessed in well-defined ways via the object’s methods. Programmers using an object can not use the data directly and risk making changes to it which could cause the object to become unreliable. The data structures within an object can be changed without affect any programs that use the object. Existing objects can be easily re-used. Programmers can build up a library of commonly used objects or purchase them from other companies. Advantages of this are : Reliability : If you purchase components they will probably have been extensively tested and can be written by experts in a particular field. Time-Saving : Re-using components means that code can be written more quickly and so less expensively. Decreased Maintenance : If you purchase components, it is the responsibility of the company you purchased them from to maintain them. As a programmer you have less of your own code to maintain. Classes and Objects A (object) CLASS is a set of objects which share a common data structure and common behaviour. You can think of a class as a template that is used to create an OBJECT. The template will contain a data structure and some methods that act on the data structure. Each object that is created from the same class will respond to the same messages/requests in an identical fashion. An OBJECT is a MODULE that consists of a data structure and some methods (behaviours) that act on the data structure. The data structure should only be accessible via the methods which provide a well-defined interface to the object i.e. a car class would be used to represent all cars in a program. A car object would represent a particular car. Classes are the basic building blocks of OOP. An object oriented program will consist of several classes, one for each different type of object. For example a car rental system might contain classes for cars, customers and loans. Each class will contain : A data structure to store information about objects of that particular type (properties). Some methods (procedures) which carry out operations on the data in the object. A PROPERTY of a class/object is an item of data that the class/object stores. A METHOD of a class/object is an action that the class/object can perform. The car class will store information about each car and define methods to modify the car list. A possible data structure and methods are : Properties / Data Structure Registration Manufacturer Model Engine Size Colour Location Number of Doors Price Per Day Methods Add_Car Delete_Car Edit_Car Get_Car_Details Usually the data structure is kept private to the object and the methods can be either private or public : Public members of a class can be accessed and called from other classes. Private members of a class can not be accessed from other classes. They can only be accessed from within the same class. Encapsulation ENCAPSUALTION is the technique that is used to combine operations (methods) and data into one unit. It allows data and methods within the unit to be hidden. It is the hiding of a data structure within an OBJECT so that programmers can only access data in the structure through the object’s methods. Proper use of encapsulation help make OOP programs reliable and reusable and makes it easier for several people to work simultaneously on different objects which will work together as one program. Code For a Class Definition For the car class, the entire data structure would be private and all of the methods would be public. A definition of the car class would start like this : Class Car { Public: Method Add_Car (Details) Method Delete_Car (Details) Method Edit_Car (Details) Method Show_Car_Details (Details) Method (procedure) definitions are public so they can be accessed from outside the class. Registration : String Manufacturer : String Model : String Engine_Size : Integer Colour : String Location : String Number_of_Doors : Integer Price_Per_Day : Real Date definitions are private so they can not be accessed from outside the class. Private: Public Method Add_Car(Details) { // Code to add a car to list. } Public Method Delete_Car(Details) { // Code to remove car from list. } Public Method Edit_Car(Details) { // Code to change the details of a car. } Public Method Delete_Car(Details) { // Code to display the details of a car. } } Key points about class definitions : The definition starts with the line XXX = Class where XXX is the name of the class. The definition is split into two parts : a class header and method definitions. In the class header the methods that will be available are listed as are the fields in the data structure. The methods are public so that other objects can call the methods. This is indicated by the command Public: before the list of method names. The data items (e.g. colour) are private so that other objects can not access them. The command Private : before the data items indicate this. Some languages assume that methods and data items are public, unless the Private: command is used. After the header, the code that will implement the methods is written. Inheritance INHERITANCE is a relationship between CLASSES where a sub-class shares the data structures and methods of its parent (or base) class. Inheritance Example : Aircraft Manufacturer An aircraft manufacturer stores information about the aircraft that it builds and maintains. The manufacturer makes different types of aircraft (e.g. commercial aeroplanes, helicopters). Much of the information that is stored about each type of aircraft is the same, but some is different. For example registration number and year of manufacturer must be stored for all aircraft but “number of missiles” only needs to be stored for fighter aircraft and “seat configuration” only needs to be stored for commercial aircraft. This type of relationship can be captured in OOP by inheritance, where one class “inherits” some of the properties of another class. The inheritance diagram below shows the relationships between different classes used by the Aircraft Manufacturer : Aircraft Aeroplanes Commercial Aeroplane Helicopter Fighter The basic definition of the Aircraft class starts like this : Class Aircraft { Public: Method AddAircraft(Details) Method DeleteAircraft(Details) Method ShowAircraft(Details) Method (procedure) definitions are public so they can be accessed from outside the class. Registration : String Year_of_Manufacture : Integer Model : String Date definitions are private so they can not be accessed from outside the class. Private: } Similar classes need to be defined for Aeroplanes, Helicopter etc. and links must be established between these classes to enable inheritances. This is part of class definition for Helicopter which inherits data from the Aircraft class : Class Helicopter extends Aircraft { Public Method AddAircraft(Details) Method ShowAircraft(Details) Private : Rotor Blades : Integer Lands on Sea : Boolean } The extends keyword indicates that this class inherits some properties/methods from the Aircraft class. The AddAircraft method in the Helicopter class is used instead of the AddAircraft method in the Aircraft class when a new helicopter is added. This is called polymorphism and the one method overrides the other. This diagram shows the inheritance between the classes in more detail. It shows the data items that are stored in each class and the data items that each class inherits from its parent classes. Aircraft Inherited Data Items : None Own Data Items : Registration Year_Of_Manufacture Helicopter Aeroplane Inherited Data Items : Registration Year_of_Manufacture Inherited Data Items : Registration Year_of_Manufacture Own Data Items : Wing_Span Number_of_Engines Own Data Items : Number_of_Rotor_Blades Rotor_Blade_Length Commercial Aeroplane Fighter Inherited Data Items : Registration Year_of_Manufacture Wing_Span Number_of_Engines Inherited Data Items : Registration Year_of_Manufacture Wing_Span Number_of_Engines Own Data Items : Seat_Configuration Galley_Type Entertainment_System Own Data Items : Number_of_Missiles Maximum_Bomb_Payload Radar_System Note that each class will also have its own methods and will inherit methods from its parent classes, but these have not been shown. Association and Containment An ASSOCIATION is a link between objects which allow them to communicate. Associations can be AGGREGATION, COMPOSITION or CONTAINMENT. CONTAINMENT means that one OBJECT can completely contain another object. e.g. a disk object could completely contain many directory or file objects, a form object may contain a number of button objects, a lest box object etc. Class MenuForm { LoadButton : Button; SaveButton : Button; Title : Label; Username : ComboBox; } AGGREGATION : When an object is created which is aggregated from other objects the other objects can continue to exist when the main object is destroyed as they are in some way independent of the main class. Fixed Aggregation : An object is composed of a set of components that do not change. Variable Aggregation : An object is composed of a set of components that can change. COMPOSITION : When an object is created which is composed of other objects the other objects are dependent on the main object. The main object owns them. If the main object is deleted the contained objects should also be destroyed. e.g. A university id composed of departments. The university owns the departments. If it ceases to exist, so do the departments. But the departments are aggregations of the professors. If the departments cease to exist the professors do not as they are independent. Note: Exam questions have never asked about the difference between Aggregation and Composition, they have only asked about Containment in general. Class Diagrams Class diagrams are different to inheritance diagram. You can use a class diagram to show inheritance, containment and Inheritance: Classes CurrentAccount and SavingsAccount inherit some properties and methods from parent class BankAccount: BankAccount CurrentAccount Looks like an inheritance diagram but with rectangles. CurrentAccount Containment: A Menu Class contains 2 Buttons, a Label and a Combo box. MenuForm Class MenuForm { LoadButton : Button; SaveButton : Button; Title : Label; Username : ComboBox; } Button Label ComboBox Note that the black diamond indicates containment. Association: Two classes are related to each other but there is no containment or inheritance. For example, a library borrowed class, loan class and book class. Borrower 1 1..* Loan 1 1..* Book Looks like an E-R diagram. Polymorphism POLYMORPHISM means that the same name is used in the class hierarchy for a method but each class may implement this method differently. i.e. A class derived from another class can respond to the same message as a parent class using a different method (but with the same name), thus producing different results. e.g. the Aircraft class might have a “Show” method which displays the details of an aircraft. The aeroplane and helicopter classes could each implement this method differently to show different information. This is polymorphism, and the method that is redefined is said to override the method in the base class. Event-Driven Programming Traditional programs, written to run with a command line interface or menu driven interface, have complete control over what order the statements in the program execute in. The main part of the program will execute the procedures that the program is composed of in an order that the programmer has determined. This is not usually possible when programs are written for a graphical user interface because the user can choose what happens when by clicking on buttons or selecting items from different controls (e.g. list box, text box). A different style of programming is therefore needed for GUIs. This is known as event driven programming. Sections of code (usually procedures) are associated with particular user actions (known as events). For example : A procedure which looks up a customer’s address and displays it on the screen could be associated with the user pressing the enter key after typing in the customer’s identity number. A procedure which prints an invoice could be associated with pressing a button to finalise the entry of an order on a form. When an event occurs the procedure or function that is associated with that event is executed. Hence the operation of the program said to be event-driven. The order in which procedures are executed is determined by the actions the user takes. In an EVENT-DRIVEN PROGRAM the sequence of program execution is determined by events triggered by the user (e.g. clicking a button, selecting an option) or operating system rather than the order of the statements in a program. Most programs written for GUIs are event-driven. Example Class Definitions Example Class Definition : Forms, Inheritance (Properties Only) A class bookingform inherits some of its properties from another class, mainform. On the form there are two buttons called canclebutton and confirmbutton together with a combobox called dateselector. Write a class definition for bookingform. class bookingform extends mainform { cancelbutton : button confirmbutton : button dateselector : combobox } Example Class Definition : Properties and Methods, Public and Private For an object-oriented program a car class needs to be declared to store details about a car. The class should store a car’s registration number, model, make and colour. Write a class definition for the class car which will allow the program to use objects of this class to add a car’s details, display a car’s details and search for a car. No other form of access by the program is allowed. class car { public : method addcar(details) method displaycar(details) method searchcar(details) private : registrationnumber : string model : string make : string colour : string enginecapacity : integer } The Exam Previous exam questions have asked you to do four different things : Provide definitions e.g. class, object, inheritance, encapsulation, polymorphism, association, containment, event-driven. State advantages of object oriented programming over procedural programming (e.g. Pascal). Draw inheritance diagrams. Give examples of properties and methods for everyday objects e.g. a spider. Key Definitions An OBJECT is a module that consists of a data structure and some methods (behaviours) that act on the data structure. A (object) CLASS is a set of objects which share a common data structure and common behaviour. ENCAPSUALTION is the technique that is used to combine operations (methods) and data into one unit. INHERITANCE is a relationship between CLASSES where a sub-class shares the data structures and methods of its parent (or base) class. POLYMORPHISM means that the same name is used in the class hierarchy for a method but each class may implement this method differently. An ASSOCIATION is a link between objects which allow them to communicate. Associations can be AGGREGATION, COMPOSITION or CONTAINMENT. CONTAINMENT means that one object can completely contain another object. In an EVENT-DRIVEN PROGRAM the sequence of program execution is determined by events triggered by the user (e.g. clicking a button, selecting an option) or operating system rather than the order of the statements in a program. WHAT DO THESE TERMS MEAN The classes inside another class only exist while the main class exists. FIXED AGGREGATION VARIABLE AGGREGATION