Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Higher Computing Science The Object Oriented Programming Paradigm Welcome to the first Advanced Higher Computing Science homework session. We're.

Similar presentations


Presentation on theme: "Advanced Higher Computing Science The Object Oriented Programming Paradigm Welcome to the first Advanced Higher Computing Science homework session. We're."— Presentation transcript:

1 Advanced Higher Computing Science The Object Oriented Programming Paradigm
Welcome to the first Advanced Higher Computing Science homework session. We're going to introduce the Object Oriented Programming Paradigm and look at how it differs from conventional Imperative programming.

2 Software development costs
In the early days of computing, machine time was extremely expensive compared to the cost of programmer time Much of the development which has taken place in software development has been made possible by the huge increase in speed and capacity of hardware. Programmer efficiency has increasingly become much more cost effective than hardware efficiency

3 Developments in Imperative programming
Use of Sub-programs (functions and procedures) Local variables Parameter passing Module Libraries Eliminating errors has always been the holy grail as far as Programming is concerned. The use of sub programs, parameters and the distinction between local and global variables were all developed in an attempt to make the task of writing software more efficient, particularly where large software projects are concerned. Paradoxically these techniques are less efficient from the point of view of the hardware they run on, although a lot of progress has been made developing compilers which optimise the machine code when converting from source code. These techniques may also seem time consuming at first when learning to code, since to begin with you are writing very short programs. You may well have asked – why write a function or a procedure for this process if we are only going to use it once anyway. The answer of course is that it makes your code more readable, and when you come to write more complex programs, using functions and procedures does actually make coding more efficient from the programmer's point of view

4 The rise of OOP OOP was developed as programs became more complex and error prone as a result. Benefits are: Robustness: Emphasis on keeping blocks of code (objects) self contained (encapsulation) Efficiency: code re-use (inheritance) Object Oriented Programming was the next step in improving programmer efficiency and attempting to eliminate errors. It could be seen as taking modularity to its logical extreme. Again the extra coding required to implement OOP programming paradigm may also seem time consuming when learning to program. but they are primarily designed to make programming more efficient when dealing with large projects and several people working together. Most modern languages require you to create classes when writing an application, but often the class is only used to create one object and you may well have asked – why do you need a class at all. OOP is worth learning now rather than later when you have developed bad coding habits, Just as meaningful variable and procedure names and internal documentation may have seemed unnecessarily laborious when you first started to code, but now you know how useful this is when debugging.

5 Classes and objects A Class definition is a blueprint which is used to create objects (called instantiation). An object is a block of code which consists of data (its Instance Variables) and operations (its Methods) Classes save development time because they can be used to create any number of objects without re-writing code. Objects make code more robust because their instance variables can only be accessed by the methods defined in the class. OOP has suffered from the fact that its main concepts have been given a large variety of different names. We're going to use the ones in bold exclusively. A class itself is a definition – it does nothing by itself, and it is only when an object is created (instantiated) from it that something useful has been made. The point of a class is that it saves re-writing code when you need another object.

6 Defining a class Decide what instance variables and methods will be needed for the objects which the class will instantiate. Use class diagrams to describe a class and its relations with other classes. A class diagram is just a visual way of describing a class or classes. It helps understanding if you can use the diagram to explain the relationship between them if you have more than one.

7 Example of a class: the Chatroom
A very simple chatroom. Its Instance Variables are its name and a string array of users. Its Methods are procedures to add a user and to remove a user. This is the standard way to create a class diagram: The top partition contains the name of the class. The middle part contains the class’s instance variables The bottom partition shows the possible methods that are associated with the class. I've kept this class deliberately simple – in a real chatroom there would be many more instance variables and methods

8 The User class A user has as its Instance Variable, the username for that user. The Methods for a user would be procedures to log in and log out. Similarly I've kept this class deliberately simple – a user would normally have more instance variables and methods

9 Class definitions A class definition looks like a record definition with an additional section where the methods are defined. Just as with records, a class definition doesn’t actually create anything. Rather, it specifies how to make individual instances of the class, called objects. The syntax for coding a class will vary from language to language, but in general a class definition will look similar to the one used for a record. If you remember from Higher, a record is a structure which can contain variables of different types. It only becomes instantiated once these variables have been given values. A class does the same thing. It describes the variables which are going to be used, but in addition describes the procedures and functions which manipulate these variables. The advantage of a class I that it creates self-contained objects – the procedures and functions only apply to the data defined within it.

10 A ChatRoom can contain several Users
A class can contain another class as a variable. In this case the Chatroom class has an array of users as one of its instance variables Notice that the relationship between the user class and the chatroom class is one of direct association. The chatroom can exist without any users in it.

11 Defining the Chatroom Class
CLASS ChatRoom IS {STRING roomName, ARRAY OF User users} METHODS PROCEDURE addUser (STRING userName) < add user to users array> END PROCEDURE PROCEDURE removeUser (STRING userName) < remove user from users array> END CLASS We will be using the Haggis reference language throughout these homework sessions. Because schools are using a wide variety of different programming languages, this was the easiest way of presenting an algorithm which everyone could use. The SCHOLAR online materials use a colour coding which is helpful for identifying different parts of the code. Remember that you will never be asked to write haggis code in an exam – you can use your own pseudocode and your preferred language code when giving examples. Because we are keeping this example simple, I've not written code for adding or removing users. I've used elision to show where it would be needed when actually coding this application.

12 Defining the User class
CLASS User IS {STRING userName} METHODS PROCEDURE login () Chatroom.addUser(THIS.userName) END PROCEDURE PROCEDURE logout () Chatroom.removeUser(THIS.userName) END CLASS Note the use of the keyword THIS which is often used in Object Oriented languages to access the instance variable belonging to the object in the class definition. So THIS refers to the class username, not an external variable. UserName is local to the User class

13 Instantiating objects from the class definitions
This is where the Object Oriented paradigm becomes useful. Multiple chatrooms can be created without re-writing code. Each chatroom has its own instance variables and methods avoiding possible confusion of data The way in which data is passed between objects (user and chatroom) is strictly controlled The self contained aspect of objects is known as Encapsulation

14 Instantiating a new music chatroom object
DECLARE musicUsers AS ARRAY OF STRING INITIALLY [] DECLARE musicRoom1 INITIALLY ChatRoom ("Pop Talk", musicUsers[]) DECLARE user1 INITIALLY User ("PartyAnimal") DECLARE user2 INITIALLY User ("BobMarley") musicRoom1.addUser (user1) musicRoom1.addUser(user2) The term instantiation means creating objects from the class definition and giving their instance variables a value. In this case we have created three objects from their respective classes: musicRoom1, user1 and user2 MusicRoom1 is instantiated with a room name and an empty musicUsers array of users User1 and user2 are instantiated with usernames, then the musicUsers array is populated with these two users using the musicRoom1 addUser procedure The term instantiation means creating objects from a class definition and giving their instance variables a value.

15 Instantiating a new music chatroom object
DECLARE chatUsers AS ARRAY OF STRING INITIALLY [] DECLARE musicRoom2 INITIALLY ChatRoom("Hip-hop",chatUsers[]) DECLARE user3 INITIALLY User ("Bill") DECLARE user4 INITIALLY User ("Joe") musicroom2.addUser(user3) musicRoom2.addUser(user4) musicRoom1.removeUser(user2) musicRoom2.addUser(user2) Now a new chatroom can be created from the same class and populated with another set of users Remember we can create as many chatrooms as we want from the ChatRoom class and as many users as we want from the User class. Each Chatroom and each user remains self contained with their own instance variables and methods Now a new chatroom can be created from the same class and populated with another set of users

16 Inheritance PrivateRoom is an extension of the ChatRoom class.
It inherits all the ChatRoom instance variables and methods but adds additional behaviour PrivateRoom is a subclass of the ChatRoom class The addUser method overrides the method with the same name in the ChatRoom superclass We can create a new class, but save writing duplicate code by making the new class inherit code from its superclass. There is a debugging advantage here as well. If we find errors in the new subclass, we only need to look at the new code, not the code which has been inherited, because we know that the superclass has already been tested.

17 Inheritance PrivateRoom is a specific type of the ChatRoom superclass
In this case PrivateRoom inherits the RoomName and users instance variables, but adds an additional password instance variable PriavateRoom inherits the adduser and removeUser methods, but adds an additional checkPass method and the addUser method overrides the method with the same name in the ChatRoom superclass I've been using a relationship diagram convention here. You can look them up here, but they are not part of the course so shouldn't appear as questions in the exam.

18 Class Diagram Relationships in UML
We'll be looking at the Unified Modelling Language in a later homework session.

19 Defining the PrivateRoom class
CLASS PrivateRoom INHERITS ChatRoom WITH {STRING password} METHODS CONSTRUCTOR() DECLARE THIS.password INITIALLY "" DCECLARE THIS.roomName INITIALLY roomName DECLARE THIS.users INITIALLY users END CONSTRUCTOR OVERRIDE PROCEDURE addUser (STRING userName) SEND "please enter password" TO DISPLAY RECEIVE password FROM KEYBOARD IF checkPass (password) THEN < add user to users array> ELSE SEND "Sorry this is a private chatroom" TO DISPLAY END IF END PROCEDURE Remember that the addUser method in the PrivateRoom class overrides the addUser method in the chatroom super-class The addUser procedure in the PrivateRoom class calls the checkPass function which returns a Boolean value A constructor is just a way of giving initial values to instance variables. A PrivateRoom object can only be created using the constructor which overrides the instance variables in the ChatRoom class

20 The checkPass function
FUNCTION checkPass (password) RETURNS BOOLEAN IF password = "secret" THEN RETURN true ELSE RETURN false END IF END FUNCTION END CLASS

21 Creating a private chatroom object
DECLARE adminUsers AS ARRAY OF STRING INITIALLY [] DECLARE adminRoom INITIALLY PrivateRoom("admin",adminUsers[]) DECLARE user5 INITIALLY User ("Admin") DECLARE user6 INITIALLY User ("Admin2") Users can join a room with the adUser command: adminRoom.addUser(user5) adminRoom.addUser(user6) Now the adminRoom object can be instantiated from the PrivateRoom class, and populated with user5 and user6 who have been instantiated from the User class.

22 Why Object Oriented programming?
Once a class has been defined, it can be used to create a number of objects. Each object is a self contained unit with strict constraints on how its data and methods interact. (encapsulation) Sub classes can be created which inherit data and methods from their superclass (inheritance)

23 Why Object Oriented programming?
Being able to use a class to create a number of objects only becomes an obvious advantage when you are in a situation where there are several instances of the same thing needed in an application. Examples might be: Chatrooms in a discussion board Playlists in a music application Customers and orders in an ecommerce application Many real world examples

24 Why Object Oriented programming?
Code is robust Development time is reduced Standardised development methodologies such as UML can be used to plan development

25 Exam questions

26 2015 Q 3a(i) By referring to the class diagram above, explain:
• the difference between a class and an object • encapsulation • inheritance

27 2015 Q 3a(i) A class defines the instance variables and methods that an object created from it should have. An object is created from a class (called instantiation) Encapsulation means that instance variables in a class are private to that class and can only be accessed using the methods in that class eg the contents of teamList can only be changed using addMember() or deleteMember() Inheritance is where a sub class inherits the instance variables and methods from its parent eg. The Athlete and Official classes inherit all of the methods and instance variables and methods from the Member class.

28 2015 Q 3a(ii) Some of the code used to define the class Team is provided below. CLASS Team IS { STRING teamName, STRING anthem, STRING flag, ARRAY OF Member teamList } METHODS CONSTRUCTOR ( STRING teamName, STRING anthem, STRING flag ) DECLARE THIS.teamName INITIALLY teamName DECLARE THIS.anthem INITIALLY anthem DECLARE THIS.flag INITIALLY flag DECLARE THIS.teamList INITIALLY [] END CONSTRUCTOR PROCEDURE addMember( Member newMember ) SET THIS.teamList TO THIS.teamList & [newMember] END PROCEDURE END CLASS

29 2015 Q 3a(ii) An instance of the Team class is to be created using the following values. Team Name Brazil Anthem Hino Nacional Brasileiro Flag Bandeira do Brasil Using the data provided and a programming language with which you are familiar, write the code used to instantiate a Team object. Your code should make use of each of the values provided. DECLARE team1 INITIALLY Team ("Brazil","Hino Nacional Brasileiro", "Bandeira do Brasil”)

30 2015 Q 3b The details of the athletes taking part in individual events will be stored in separate arrays of objects. For example, the longjumpM array will store the details of all 32 male athletes taking part in the long jump event. Using a programming language with which you are familiar, write the code used to create the array of objects used to store details of the 32 male athletes in the long jump event. DECLARE longjumpM AS ARRAY OF Athlete * 32

31 2015 Q 3c Two introduce methods have been written for the Member and Athlete classes respectively. # Version in Member class PROCEDURE introduce() SEND “Hello, my name is “ & THIS.firstName TO DISPLAY END PROCEDURE # Version in Athlete class OVERRIDE PROCEDURE introduce() SEND “I’m an athlete on the team” TO DISPLAY Note the Override introduce() procedure

32 2015 Q 3c(i) A new Team object called myTeam has been created. The following calls have been made to add Ali, Omar and Nour to the team. myTeam.addMember( Athlete(“Ali” <only firstName needed here> )) myTeam.addMember( Member(“Omar” <only firstName needed here> )) myTeam.addMember( Official(“Nour” <only firstName needed here>)) Write down the output displayed by the following procedure call:  myTeam.introduce() Hello, my name is Ali I’m an athlete on the team Hello, my name is Omar Hello, my name is Nour

33 2015 Q 3c(ii) Use object oriented terminology to explain the operation of the procedure call: myTeam.introduce() myTeam.addMember( Athlete(“Ali”)) myTeam.addMember( Member(“Omar” )) myTeam.addMember( Official(“Nour”)) Athlete and Official inherit the instance variables and methods from the Member super-class but the introduce method in the Athlete sub-class overrides the one in the Member class so the additional text is displayed for Ali

34 Specimen Paper Q1a This question is slightly confusing because it uses the Object class as an example. It also should have blank sections for the Object and Weapon classes to show that there are no methods associated with them

35 Specimen Paper Q1a a) Explain why the Object class contains position variables but the other classes do not.

36 Specimen Paper Q1a Since Weapon, Character and Enemy are subclasses of the Object class then the Object instance variables are inherited. The name instance variable will be inherited as well of course.

37 Specimen Paper Q1b Describe what is meant by encapsulation, with reference to how it has been applied in the Character class.

38 Specimen Paper Q1b The Object instance variables would be hidden and inaccessible outside the Character subclass. Code within the methods of the class, such as Walk_one_step, can only manipulate the instance variables of an instantiation of that class eg the position coordinates. Objects are self-contained

39 Specimen Paper Q1c(i) (i) One opinion is that the classes are inefficiently structured. Explain why this could be true.

40 Specimen Paper Q1c(i) There is repetition of many lines of code, both instance variables and methods in both the Character and Enemy subclasses.

41 Specimen Paper Q1c(ii) Describe how the classes could be restructured to be more efficient.

42 Specimen Paper Q1c(ii) Create a subclass, eg Agent, and place all common instance variables and methods in that subclass. Create two new subclasses of agents, ie Character and Enemy with only their unique instance variables, ie strategy for Enemy and id for Character.

43 Specimen Paper Q1c Character and Enemy inherit the instance variables of the Agent superclass. Agent inherits the instance variables of the Object class.

44 Specimen Paper Q1d The program, based on the above classes, contains the following lines of code: 1. SET davina TO <create an object of the Character class> 2. SET modzilla TO <create an object of the Enemy class> 3. davina.Attack_enemy(modzilla) The purpose of line 3 is for davina to attack modzilla. Explain, using object-oriented terminology, how this is achieved.

45 Specimen Paper Q1d 1. SET davina TO <create an object of the Character class> 2. SET modzilla TO <create an object of the Enemy class> 3. davina.Attack_enemy(modzilla) The Attack_enemy method of the davina object is called, with modzilla as the actual parameter.

46 2013 Q 4a Explain the purpose of the sections marked A and B in a class definition

47 2013 Q 4a Section A contains the instance variables (data)which store the characteristics of an object. Section B contains the methods which can manipulate these instance variables.

48 2013 Q4b

49 2013 Q4b(i) The Rectangle class will be a subclass of the Shape class with additional instance variables and methods defined within it. Can you describe how the class diagram for a rectangle or a circle would look?

50 2013 Q4b(i) Note that Rectangle and Circle inherit the instance variables linewidth and fillcolour and the fill method from the shape class

51 2013 Q4b(ii) Because the Rectangle class inherits all its code from the Shape class, coding time will be reduced Error location can be improved because if there is a problem with a subclass, only the additional methods in subclasses needs to be checked not inherited code .

52 2011 Q5b A programmer is developing software that requires the use of several stacks. The programmer creates a Stack class. (i) State the purpose of two instance variables required for the implementation of the Stack class. (ii) Describe two methods that the Stack class would contain.

53 2011 Q5b

54 2011 Q5c Describe two advantages of programming in an object-oriented language when using several stacks compared to how a they would be implemented in a procedural language.

55 2011 Q5c Reducing development time: In OOP the programmer can create as many instances from the Stack class as required, reducing development time compared to redefining much of the code for a new stack in a procedural language. Creation of a subclass of stacks that inherits code from a superclass means that only additional states and methods need be defined reducing the additional coding/development time compared to using a procedural language. Maintainability and debugging: In OOP the instances of a Stack class would be error free/or all contain the same error, making debugging code/locating errors easier than in a procedural language. Sub and superclasses means that the location of errors can be traced by their presence in all objects or just those of a subclass, reducing debugging/testing/maintenance activities.


Download ppt "Advanced Higher Computing Science The Object Oriented Programming Paradigm Welcome to the first Advanced Higher Computing Science homework session. We're."

Similar presentations


Ads by Google