1 / 82

Introduction to Classes and Objects Initializing Objects Making Use of Classes in Algorithms Class Examples

Lecture 18. Introduction to Classes and Objects Initializing Objects Making Use of Classes in Algorithms Class Examples. Introduction to Classes and Objects. The Scenario. We want to provide a “black box” approach to reusable components…. Don’t know how it works, but it works!. Input.

drew
Download Presentation

Introduction to Classes and Objects Initializing Objects Making Use of Classes in Algorithms Class Examples

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. Lecture 18 Introduction to Classes and Objects Initializing Objects Making Use of Classesin Algorithms Class Examples

  2. Introduction to Classes and Objects

  3. The Scenario • We want to provide a “black box” approach to reusable components… Don’t know howit works, but itworks! Input Output

  4. The Scenario • We want to create reusable components for other programmers to use. • They are focused on their work and don’t want to know the details of how our component works. • They are also busy trying to do their work, so maybe they’ll take shortcuts and “hack.” • We want to provide services to them but protect the implementation details of our components.

  5. Classes • A class is the fundamental unit of object-oriented programming. • It allows us to implement ADTs, combining both data and operations into one logical bundle.

  6. Objects • Once we have a class defined, we can then declare any number of objects of that class. For example: • Once we have a queue class defined, we can then declare any number of queue objects. • Each queue object will then have all the data and procedural abstractions needed for a queue.

  7. Classes and Objects • A class is like a blueprint: • An object is an instantiated class (like a building):

  8. Classes vs. Objects Class refers to the template by which we implement an ADT’s functionality. Thus, it is analogous to data type: it is only a definition or template. Object refers to a specific instance of the class. Thus, it is analogous to variable: it is an instance of a template. Class : Object :: Type : Variable

  9. Classes Allow for Reuse! Algorithms which make use of the queue class (by declaring instances of the queue, or objects) are clients who obtain services: algorithm Movie_Theatre algorithm Restaurant algorithm Check-out_Line The authors of these algorithms can instantiate and use queues without writing them!

  10. Components of a Class • The individual data elements of a class are referred to as attributes of the class. • The entire collection of data maintained within an object is referred to as the stateof the object. • The operations (procedures and functions) that are provided by the class (and thus allowed on the data) are called the methodsof the class.

  11. Controlling Visibility • Recall we want to protect the implementation of the class. • Users shouldn’t need to know how it works • Users shouldn’t be able to violate the behaviors (may only do what we allow them). • Encapsulation allows us to hide the implementation details.

  12. Public vs. Protected Protected Public

  13. Visibility Within a Class The rest of the algorithm Public Section (Interface) Protected Section(Implementation)

  14. Anatomy of a Class Classes have two sections: • Public - the specification of the "visible” part of the class • Protected - the specification of the "hidden” part of the class

  15. Public Section • Contains everything that the client algorithm needs to know to use the class • Is the visible part of the class • Defines the interface and contract with the user (algorithm) • Contains the header lines of those methods that are available for clients of the class to call.

  16. Protected Section • Contains the detailsof the implementation of the class • Cannot be seen by the client algorithm • Hides attributes and method implementation • Contains all method declarations and implementations.

  17. Interactions Client Algorithm Public Module Definitionsand Contract Supplier Object Protected Data & Implementation of Modules

  18. Encapsulation and Hiding A client algorithm can see only the public section of the class. Aclient has no idea what is within the protected section. A client algorithm can interact with an object only by calling the methods listed in the public section of the class. A client algorithm cannot directly access any of the data within an object. It may “get at” data only via calls to public methods.

  19. Public vs. Protected Methods Clients may call any/all of the three public methods. Clients don’t know the hidden method exists; they cannot call it. Some Class publicmethod 1 publicmethod 3 class data publicmethod 2 a protectedmethod

  20. Protected Methods A protected method is one which is defined in the protected section that does not have its header line in the public section. Clients don’t even know it exists. Such a method may only be called by other methods within the protected section.

  21. Structure of a Class Definition class <identifier> public <method definitions and contracts> protected <constants> <type definitions> <attribute declarations> <method implementations> endclass // <identifier>

  22. A Bus Class Example Bus Initialize MAX_PASSENGERS Current Add Passengers Implementation RemovePassengers Number of Passengers

  23. class Bus public procedure Initialize // contract here procedure AddPassengers (to_add iot in num) // contract here function NumPassengers returnsa num // contract here procedure RemovePassengers (to_remove iot in num) // contract here protected MAX_PASSENGERS is 50 current isoftype num procedure Initialize current <- 0 endprocedure // Initialize

  24. procedure AddPassengers (to_add iot in num) if (current + to_add <= MAX_PASSENGERS) then current <- current + to_add endif endprocedure // AddPassengers function NumPassengers returnsa num NunPassengers returns current endfunction // NumPassengers procedure RemovePassengers (to_remove iot in num) if (current >= to_remove) then current <- current – to_remove endif endprocedure // RemovePassengers endclass // Bus

  25. Recipe for Writing a Class • Write shell/template • Decide on what the user needs to know about - PUBLIC • Specify the protected data • Diagram & think of sample algorithm • Write public section with contract information • Write protected section with implementation details

  26. Attribute Visibility in the Protected Section Variables declared at the global level of the protected section can be directlyaccessed throughout the protected section without passing them via parameter. protected current isoftype num . . . procedure AddPassengers (to_add iot in num) if (current + to_add <= MAX_PASSENGERS) then current <- current + to_add endif endprocedure // AddPassengers function NumPassengers returnsa num NunPassengers returns current endfunction // NumPassengers . . .

  27. Attribute Visibility in the Protected Section • Allow direct access, bypassing parameters! • May want clients of the class to be able to call methods • Don't want clients to know the details of the protected section's data representation. • If method parameter lists included data that's protected, then would be telling the client about that representation. • So, allow direct access withinprotected • Still have encapsulation (the class itself)

  28. Summary • Classes implement ADTs • An object is an instance of a class • Encapsulation allows for the protection of details within the class • Public section provides interface • Protected section provides implementation • Attributes declared at the global level of the protected section may be directly accessed within any method in the protected section.

  29. Questions?

  30. Initializing Objects

  31. The Scenario • You’ve defined a Queue class and now want to create an instance of that class. • There are some attributes which should be initialized when an object is created. • We’d like to initialize our Head and Tail pointers to NIL. • But the algorithm shouldn’t know about the pointers!

  32. Need to Initialize • Our Queue class will thus need a method that “sets things up” when an object is created. • Different languages handle this differently. • We’ll use a normal method that must be invoked like any other…

  33. “A Method By Any Other Name…” • An initialization method is just like any other method. • For clarity and convenience, we always use the identifier Initialize for such methods.

  34. Initialize Common but Not Required • Most classes have attributes that require some initial values. • We expect most classes to have initialization methods. • But it’s not required.

  35. Initialize In the Class Definition class Initialize_Example public . . . procedure Initialize (<parameters>) // contract information . . . protected . . . procedure Initialize (<parameters>) <implementation> endprocedure // Initialize endclass

  36. Invoking the Initialize Method • In the algorithm, we invoke (or call) the Initialize method just as any other method. • It is assumed that Initialize is only called once, but there is no rule to enforce this. • The algorithm must explicitly call the initialize method for each object that has attributes that need to be initialize.

  37. An Example In the algorithm: MyQueue isoftype Queue MyQueue.Initialize In the class definition: procedure Initialize head <- NIL tail <- NIL endprocedure // Initialize

  38. Another Example In the algorithm: MyAirplane isoftype Plane MyAirplane.Initialize(“Delta 955”) In the class definition: procedure Initialize(flight_name iot in string) altitude <- 0 current_flight <- flight_name endprocedure // Initialize

  39. Summary • Very often, objects have attributes that need some initial values. • Thus these classes need some method to set these attributes. • Different languages handle this differently: • Some have “special” methods that are automatically executed. • We’ll treat the Initialize method like any other method and call it from the algorithm for each object created.

  40. Questions

  41. Making Use of Classesin Algorithms

  42. The Scenario • You need to create a simulation of an airport. • A coworker has developed an airplane class you’d like to use in your algorithm. • How do we “get at” the airplane class? • Notice we don’t have access to modify the class, just make use of it.

  43. Importing the Class • Algorithms and class definitions often reside in separate computer files. • Recall that a benefit of Object-Oriented Programming is re-use via class libraries • We need the ability to import a class into our algorithm or another class • The “uses” clause allows this import.

  44. The “Uses” Clause algorithm <Algorithm Name> uses <Class Name>, <Class Name>, . . . . . . endalgorithm // <Algorithm Name> class <Class Name> uses <Other Class Name> . . . endclass // <Class Name>

  45. An Example Having previously defined an Airplane class, the algorithm can make use of the class and create objects of the class as follows: algorithm Airport uses Airplane Cessna, Prop isoftype Airplane . . .

  46. A More Complex Example algorithm BigAirport uses Airplane, Helicopter, FlightController Plane1, Plane2 isoftype Airplane ControlDeck isoftype FlightController . . . endalgorithm

  47. Classes and Objects • A class is like a blueprint: It is analogous to data type • An object is an instantiated class (like a building): It is analogous to variable Class : Object :: Type : Variable

  48. Creating Objects • Once the algorithm has imported the class definition, then it can create objects of the class. • Objects are created just as any variable: <Object Identifier> isoftype <Class Name> For example: MyPlane, YourPlane isoftype Airplane ControlDeck isoftype FlightController

  49. Accessing Methods of Objects • After instantiating a class and creating an object in the algorithm, we want to make use of its methods. • There are many methods in the class, so how do we access the one we want? • Just as fields of a record, we access the methods in an object using the dot (.) operator.

  50. Invoking Methods of an Object algorithm Example uses MyClass MyObject isoftype MyClass MyObject.Initialize MyObject.<Any Method in Public Section> . . . endalgorithm

More Related