1 / 205

Introduction to Classes: Abstraction and Encapsulation in Object-Oriented Programming

This chapter provides an overview of structures, classes, and abstract data types in object-oriented programming. It discusses the attributes and behaviors of objects, as well as encapsulation and access modifiers. It also covers the declaration and definition of member functions within a class, and the creation and usage of objects.

joelt
Download Presentation

Introduction to Classes: Abstraction and Encapsulation in Object-Oriented Programming

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. Chapter 10 Defining Classes

  2. Overview 10.1 Structures ---- Object Oriented Programming 10.2 Classes 10.3 Abstract Data Types 10.4 Introduction to Inheritance

  3. Objects are used to model real-world things. You can think of an object as a rather complex variable that contains multiple chunks of data

  4. Let’s consider an object that represents a time. Real world objects have attributes An object’s attributes describe its “state of being” seconds minutes am/pm hours

  5. We hide the data from anyone outside of the object by making it “private” Joe WageEarner 12356 $12.50 40 A Time object

  6. The attributes of an object are stored inside the object as data members. The hour value is stored as an integer 3 The minute value is stored as an integer 35 pm am or pm is stored as a string An “Time” object

  7. An object also has behaviors behaviors define how you interact with the object What can you do with a time? set the hours Get the hours

  8. Behaviors are expressed as methods that give us controlled access to the data. These are “public” so that we can see them. Joe WageEarner 12356 getHour ( ) setHour( ) $12.50 40 An “Time” object

  9. Then we write statements that send messages to the objects Joe WageEarner joe.getHours( ); 12356 getHour ( ) setHour ( ) $12.50 40 An “Time” object named joe

  10. An Object’s Attributes and Behaviors Should Work Together this is called cohesion

  11. Encapsulation • Encapsulation is • Combining a number of items, such as variables and functions, into a single package such as an object of a class

  12. Encapsulation Time object getHour( ) member methods are declared as public calling method we should not allow code outside of the object to reach in and change the data directly. Instead, we call methods in the object to do it for us. hour minute member data is declared as private The terms public and private are called access modifiers

  13. Introduction to Classes • A class is said to be an abstraction of the real world object that we are modeling. • Classes are sometimes called Abstract Data Types. • Class: a programmer-defined data type used to define objects • It is a pattern for creating objects ex: string fName, lName; creates two objects of the string class

  14. Notice the required ; Introduction to Classes • Class declaration format: class className { declaration; declaration; };

  15. Access Specifiers • Used to control access to members of the class. • Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class

  16. Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; Access specifiers

  17. More on Access Specifiers • Can be listed in any order in a class • Can appear multiple times in a class • If not specified, the default is private

  18. Defining Member Functions • Member functions are part of a class declaration • Can place entire function definition inside the class declaration or • Can place just the prototype inside the class declaration and write the function definition after the class

  19. Types of Member Functions • Acessor, get, getter function: uses but does not modify a member variable ex: getSide • Mutator, set, setter function: modifies a member variable ex: setSide

  20. Defining Member Functions Inside the Class Declaration • Member functions defined inside the class declaration are called inline functions • Only very short functions, like the one below, should be inline functions int getSide() { return side; }

  21. inline functions Inline Member Function Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } };

  22. Defining Member Functions After the Class Declaration • Put a function prototype in the class declaration • In the function definition, precede the function name with the class name and scope resolution operator (::) int Square::getSide() { return side; }

  23. Conventions and a Suggestion Conventions: • Member variables are usually private • Accessor and mutator functions are usually public • Use ‘get’ in the name of accessor functions, ‘set’ in the name of mutator functions Suggestion: calculate values to be returned in accessor functions when possible, to minimize the potential for stale data

  24. Creating and Using Objects • An object is an instance of a class • It is defined just like other variables Square sq1, sq2; • It can access members using dot operator sq1.setSide(5); cout << sq1.getSide();

  25. 10.2 Classes

  26. Classes • A class is a data type whose variables are objects • The definition of a class includes • Description of the kinds of values of the membervariables • Description of the member functions • A class description is somewhat like a structure definition plus the member variables

  27. A Class Example • To create a new type named DayOfYear as a class definition • Decide on the values to represent • This example’s values are dates such as July 4using an integer for the number of the month • Member variable month is an int (Jan = 1, Feb = 2, etc.) • Member variable day is an int • Decide on the member functions needed • We use just one member function named output

  28. Class DayOfYear Definition • class DayOfYear { public: void output( ); int month; int day; }; Member Function Declaration

  29. Defining a Member Function • Member functions are declared in the classdeclaration • Member function definitions identify the classin which the function is a member • void DayOfYear::output() {cout << “month = “ << month << “, day = “ << day << endl; }

  30. Member Function Definition • Member function definition syntax:Returned_TypeClass_Name::Function_Name(Parameter_List){ Function Body Statements} • Example: void DayOfYear::output( ) {cout << “month = “ << month << “, day = “ << day << endl; }

  31. The ‘::’ Operator • ‘::’ is the scope resolution operator • Tells the class a member function is a member of • void DayOfYear::output( ) indicates that function output is a member of the DayOfYear class • The class name that precedes ‘::’ is a type qualifier

  32. ‘::’ and ‘.’ • ‘::’ used with classes to identify a member void DayOfYear::output( ) { // function body } • ‘.’used with variables to identify a member DayOfYear birthday; birthday.output( );

  33. Calling Member Functions • Calling the DayOfYear member function outputis done in this way: DayOfYear today, birthday; today.output( ); birthday.output( ); • Note that today and birthday have their own versions of the month and day variables for use by the output function Display 10.3 (1) Display 10.3 (2)

  34. Problems With DayOfYear • Changing how the month is stored in the classDayOfYear requires changes to the program • If we decide to store the month as three characters (JAN, FEB, etc.) instead of an int • cin >> today.month will no longer work becausewe now have three character variables to read • if(today.month == birthday.month) will no longerwork to compare months • The member function “output” no longer works

  35. Ideal Class Definitions • Changing the implementation of DayOfYear requires changes to the program that uses DayOfYear • An ideal class definition of DayOfYear could be changed without requiring changes tothe program that uses DayOfYear

  36. Fixing DayOfYear • To fix DayOfYear • We need to add member functions to use when changing or accessing the member variables • If the program never directly references the member variables, changing how the variables are stored will notrequire changing the program • We need to be sure that the program does not ever directly reference the member variables

  37. “Setter”Methods they are usually named “set” plus the name of the instance variable they will store the value in. void Time::setHour(int hr) { hour = hr; } setters never return anything setters always take a parameter

  38. “Getter”Methods getters take no parameters getters always return something int Time::getHour( ) const { return hour; } The const keyword is required to tell the compiler that the function does not alter the object. they are usually named “get” plus the name of the instance variable they will return the value of.

  39. Public Or Private? • C++ helps us restrict the program from directly referencing member variables • private members of a class can only be referenced within the definitions of member functions • If the program tries to access a private member, thecompiler gives an error message • Private members can be variables or functions

  40. Private Variables • Private variables cannot be accessed directly by the program • Changing their values requires the use of publicmember functions of the class • To set the private month and day variables in a new DayOfYear class use a member function such as void DayOfYear::set(int new_month, int new_day) { month = new_month; day = new_day; }

  41. Public or Private Members • The keyword private identifies the members of a class that can be accessed only by member functions of the class • Members that follow the keyword private are private members of the class • The keyword public identifies the members of a class that can be accessed from outside the class • Members that follow the keyword public are public members of the class

  42. A New DayOfYear • The new DayOfYear class demonstrated in Display 10.4… • Uses all private member variables • Uses member functions to do all manipulation of the private member variables • Member variables and member function definitions can bechanged without changes to theprogram that uses DayOfYear Display 10.4 (1) Display 10.4 (2)

  43. Using Private Variables • It is normal to make all member variables private • Private variables require member functions to perform all changing and retrieving of values • Accessor functions allow you to obtain the values of member variables • Example: get_day in class DayOfYear • Mutator functions allow you to change the valuesof member variables • Example: set in class DayOfYear

  44. General Class Definitions • The syntax for a class definition is • class Class_Name{ public: Member_Specification_1 Member_Specification_2 … Member_Specification_3 private: Member_Specification_n+1 Member_Specification_n+2 …};

  45. Declaring an Object • Once a class is defined, an object of the class isdeclared just as variables of any other type • Example: To create two objects of type Bicycle: • class Bicycle { // class definition lines }; Bicycle my_bike, your_bike;

  46. Program Example:BankAccount Class • This bank account class allows • Withdrawal of money at any time • All operations normally expected of a bank account (implemented with member functions) • Storing an account balance • Storing the account’s interest rate Display 10.5 ( 1) Display 10.5 ( 3) Display 10.5 ( 2) Display 10.5 ( 4)

  47. Calling Public Members • Recall that if calling a member function from the main function of a program, you must includethe the object name: account1.update( );

  48. Calling Private Members • When a member function calls a private member function, an object name is not used • fraction (double percent); is a private member of the BankAccount class • fraction is called by member function update void BankAccount::update( ) { balance = balance + fraction(interest_rate)* balance; }

  49. Constructors • A constructor can be used to initialize membervariables when an object is declared • A constructor is a member function that is usually public • A constructor is automatically called when an objectof the class is declared • A constructor’s name must be the name of the class • A constructor cannot return a value • No return type, not even void, is used in declaring or defining a constructor

More Related