Encapsulation and Abstraction ppt

34 131 0
  • Loading ...
    Loading ...
    Loading ...

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Tài liệu liên quan

Thông tin tài liệu

Ngày đăng: 01/08/2014, 09:21

Encapsulation and Abstraction Chapter 4 Objects contain data and methods to send and receive messages. Data members of objects can have a different scope or visibility. You use access specifier to define the scope of data member and method. This chapter introduces the concept of abstraction and encapsulation. It discusses the implementation of encapsulation by using access specifiers. It also explains the concept of using methods. In addition, the chapter also discusses the static variables and static functions. In this chapter, you will learn to:  Define abstraction and encapsulation  Implement encapsulation by using access specifiers  Use methods  Use static variables and static functions Objectives Encapsulation and Abstraction 4.3 ¤NIIT Abstraction and encapsulation are important features of any OOPs language. Abstraction involves extracting only the relevant information. Encapsulation involves packaging one or more components together. Consider the following example: An automobile salesperson is aware that different people have different preferences. Some people are interested in the speed of a car, some in its price, some in the engine, and the some in its style. Although all of them want to buy a car, each of them is interested in a specific attribute or feature. The salesman knows all the details of a car, but he presents only the relevant information to a potential customer. As a result, the salesman practices abstraction and presents only relevant details to customer. In other words, abstraction means ‘looking for what you want’ in an object or a class. Consider abstraction from the perspective of a programmer who wants a user to be able to add items to a list. However, the detail of how a particular task in a program is accomplished is hidden. Abstraction does not mean that information is unavailable. It means that all the information exists, but only the relevant information is provided to the user. Encapsulation literally means ‘to enclose in or as if in a capsule’. Encapsulation is defined as the process of enclosing one or more items within a physical or logical package. It involves preventing access to nonessential details. For example, when you plug in the cord of the vacuum cleaner and turn on the switch, the vacuum cleaner starts. You do not see the complex processes needed to actually convert electricity into suction power. In other words, the exact working of the cleaner has been encapsulated. Therefore, encapsulation is also explained as information hiding or data hiding because it involves hiding many of the important details of an object from the user. Abstraction and encapsulation are different but related features. Abstraction enables you to make the relevant information visible. Encapsulation enables you to package information to implement the desired level of abstraction. Therefore, encapsulation assists abstraction by providing a means of suppressing the nonessential details. Encapsulation allows some information to be hidden but it also allows some information to be visible. Introducing Abstraction and Encapsulation Defining Abstraction Defining Encapsulation 4.4 Encapsulation and Abstraction ¤NIIT An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have one or more classes. You may want some members of a class to be accessible to other classes. But, you may not want some other members of the class to be accessible outside the class. It is the privilege of the programmer to decide the use of access specifiers to implement encapsulation and abstraction in C#. Consider the world of modern advertising. Viewers are bombarded with hundreds of advertising messages every day. If they were to listen to, understand and respond to all of them, they would probably not have much time and energy left for anything else. Instead, they concentrate only on messages that are of specific interest to them. Thus, for example, if they want to buy a refrigerator they will pay attention to the advertisements that feature refrigerators. Similarly, a housewife would typically pay attention to the size, ease of handling, and durability of a vacuum cleaner. She would not be interested in the gadgetry inside it, which is in the purview of the maintenance man. Sales personnel may concentrate on entirely different factors. There is a term given to the preceding process: abstraction. You use various types of access specifiers to specify the extent of the visibility of a class member. C# supports the following access specifiers:  public  private  protected  internal  protected internal The public Access Specifier The public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any member that is declared public can be accessed from outside the class. Types of Access Specifiers Implementing Encapsulation by Using Access Specifiers Encapsulation and Abstraction 4.5 ¤NIIT The following is an example of the use of the public access specifier: using System; class Car { private string CarColor; //Since the variable is private, it //cannot be accessed outside the class definition. } class Bike { public string BikeColor; //Since the variable is public, it //can be accessed outside the class definition. } class Result { static void Main(string[] args) { Car Ford = new Car(); ; Bike Honda = new Bike(); /* The . operator is used to access member data and functions */ Ford.CarColor = "red"; /* Error! Cannot access private members*/ Honda.BikeColor = "blue"; Console.ReadLine(); } } In the preceding example, the CarColor variable cannot be accessed from any function outside the Car class. On the other hand, the BikeColor variable is a public member. Therefore, it can be accessed from outside the class. The following is another example of the use of the public access specifier: using System; class Car { public string Color; public void Honk() { Console.WriteLine("BEEP BEEP!" ); } } class Result { static void Main(string[] args) { Car Ford = new Car(); ; Ford.Honk(); //Displays BEEP BEEP! Console.ReadLine(); } } 4.6 Encapsulation and Abstraction ¤NIIT In the preceding example, the Honk() function will be accessible from anywhere in the program and can be accessed by using the objects of the Car class. The private Access Specifier The private access specifier allows a class to hide its member variables and member functions from other class objects and functions. Therefore, the private member of a class is not visible outside a class. If a member is declared private, only the functions of that class can access the member. Even the instance of the class cannot access its private members. Therefore, the data is hidden and cannot be altered by any function other than the member functions of the class. The following is an example of the use of private access specifier: using System; class Car { private string Model; void Honk() { Console.WriteLine("PARRP PARRP!"); } public void SetModel() { Console.WriteLine("Enter the model name: "); Model = Console.ReadLine(); } public void DisplayModel() { Console.WriteLine("The model is: {0}", Model); } } class Display { static void Main(string[] args) { Car Ford = new Car(); Ford.SetModel(); //Accepts the model name Ford.DisplayModel(); //Displays the model name Ford.Honk(); //error! private members cannot be accessed outside the class definition Console.WriteLine(Ford.Model); //error! private members cannot be accessed outside the class definition } } Encapsulation and Abstraction 4.7 ¤NIIT In the preceding example, the SetModel() and DisplayModel() functions can be called from the Ford object, created in the Main() function because these are public member functions. Similarly, the Honk() function cannot be accessed through the Ford object because it is a private member function. When you do not specify any data member as public, protected, or private, then the default access specifier for a data member is private. In the following example, the data member Model is private, even though it has not been specified explicitly: class Car { char Model; } The protected Access Specifier This specifier allows a class to hide its member variables and member functions from other class objects and functions, except the child class. The protected access specifier becomes important while implementing inheritance. The following example shows that the protected member of the class will have the same visibility as a private member of the class: using System; class Car { protected string Model; void Honk() { Console.WriteLine("PARRP PARRP!"); } public void SetModel() { Console.WriteLine("Enter the model name: "); Model = Console.ReadLine(); } public void DisplayModel() { Console.WriteLine("The model is: {0}", Model); } } class Display { static void Main(string[] args) 4.8 Encapsulation and Abstraction ¤NIIT { Car Ford = new Car(); Ford.SetModel(); //Accepts the model name Ford.DisplayModel(); //Displays the model name Ford.Honk(); /*error! private members cannot be accessed outside the class definition */ Console.WriteLine(Ford.Model); /*error! protected members cannot be accessed*/ //outside the class definition } } In the preceding example, the SetModel() and DisplayModel() functions can be called from the Ford object defined in the Main() function. However, the Model variable cannot be accessed through the Ford object because it is a protected member variable. Similarly, the Honk() function cannot be accessed through the Ford object because it is also a private member function. The internal Access Specifier The internal access specifier allows a class to expose its member variables and member functions to other functions and objects. Any member that is declared internal can be accessed from any class or method defined within the application in which the member is defined. The default access specifier for a class is internal. The following is an example of the use of the internal access specifier: using System; class Car { private string CarColor; //Since the variable is private, it cannot be accessed outside the class //definition. internal void Honk() { Console.WriteLine("BEEP BEEP!" ); } } class Bike { internal string BikeColor;//Since the variable is internal, it can //be accessed outside the class //definition. } class Result { static void Main(string[] args) { Encapsulation and Abstraction 4.9 ¤NIIT Car Ford = new Car(); ; Bike Honda = new Bike(); Ford.CarColor = "red"; /* Error! Cannot access private members*/ Honda.BikeColor = "blue"; Ford.Honk(); //Displays BEEP BEEP! Console.ReadLine(); } } In the preceding example, the CarColor variable cannot be accessed from any function outside the Car class. On the other hand, the BikeColor variable is an internal member. Hence, it can be accessed from outside the class. Also, the Honk() function will be accessible from anywhere in the program and can be accessed by using the objects of the Car class. The protected internal Access Specifier This specifier allows a class to show its member variables and member functions to the containing class, derived classes, or to classes within the same application. The protected internal access specifier becomes important while implementing inheritance. The following example shows that the protected internal member of the class will have the same visibility as a private member of the class: using System; class Car { protected internal string Model; void Honk() { Console.WriteLine("PARRP PARRP!"); } public void SetModel() { Console.WriteLine("Enter the model name: "); Model = Console.ReadLine(); } public void DisplayModel() { Console.WriteLine("The model is: {0}", Model); } } class Display { static void Main(string[] args) 4.10 Encapsulation and Abstraction ¤NIIT { Car Ford = new Car(); Ford.SetModel(); //Accepts the model name Ford.DisplayModel(); //Displays the model name Ford.Honk(); /*error! private members cannot be accessed outside the class definition */ Console.WriteLine(Ford.Model); /*error! protected internal members cannot be accessed outside*/ the class definition } } In the preceding example, the SetModel() and DisplayModel() functions can be called from the Ford object defined in the Main() function. However, the Model variable cannot be accessed through the Ford object because it is a protected internal member variable. Similarly, the Honk() function cannot be accessed through the Ford object because it is also a private member function. The following table shows the visibility of the class members for the access specifiers. Access Specifiers Visible to objects of other classes inside the namespace collection Visible to objects of child classes within the namespace collection Visible to objects of other classes outside the namespace collection Visible to objects of child classes outside the namespace collection public Yes Yes Yes Yes private No No No No protected No Yes No Yes internal Yes No No No protected internal Yes Yes No No Visibility of Class Members [...]... Tools Visual Studio 2005 Command Prompt to open the Visual Studio 2005 Command Prompt window In the Visual Studio 2005 Command Prompt window, move to the location where the program file is saved Compile the program file by using the following command: 9 Execute the compiled program as: 7 csc Area.cs Area.exe 10 Verify the output of the executed program 4.12 Encapsulation and Abstraction NIIT The output... Microsoft Visual Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt to open the Visual Studio 2005 Command Prompt window In the Visual Studio 2005 Command Prompt window, move to the location where the program file is saved 4.30 Encapsulation and Abstraction NIIT 8 Compile the program file by using the following command: csc FunctionCount.cs 9 Execute the compiled program as: FunctionCount.exe... static int Main(string[] args) { 4.28 Encapsulation and Abstraction NIIT StaticExample s = new StaticExample(); s.count(); s.count(); s.count(); Console.WriteLine("The value of variable is {0}", StaticExample.display()); Console.ReadLine(); return 0; } } The output of the preceding code is as follows Output of the Static Function Program NIIT Encapsulation and Abstraction 4.29 Activity: Counting the... NIIT Encapsulation and Abstraction 4.13 Using Methods A method is a set of one or more program statements, which can be executed by referring to the method name Methods play a key role in modular programming When a complex application is divided into methods, code is more flexible and easy to maintain and to debug Methods are useful for performing repetitive tasks, such as fetching specific records and. .. statement is true or false: Abstraction represents the essential characteristics of an object or classes that differentiate it from other objects or classes 4.32 Encapsulation and Abstraction NIIT Summary In this chapter, you learned that: Abstraction is the process of reducing information content in order to retain only the relevant information for a particular purpose Encapsulation is the process... member variables and functions of a particular class The public access specifier allows a class to expose its member variables and member functions to other functions and objects The private access specifier allows a class to hide its member variables and member functions from other class functions and objects The protected access specifier allows a class to hide its member variables and member functions... Console.ReadLine(); 4.24 Encapsulation and Abstraction NIIT } } 3 4 5 6 Select File Save to save the program file The Save As dialog box opens Enter “SwapNumber.cs” in the File name text box Click the Save button in the Save As dialog box Select Start All Programs Microsoft Visual Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt to open the Visual Studio 2005 Command Prompt window 7 In... Visual Studio 2005 Command Prompt window, move to the location where the program file is saved 8 Compile the program file by using the following command: csc SwapNumber.cs 9 Execute the compiled program as: SwapNumber.exe 10 Verify the output of the executed program The following window verifies the output of the executed program Output of the Swap Number Program NIIT Encapsulation and Abstraction 4.25 Using... Main(string[] args) { Calculator cal = new Calculator(); // The following statement is calling the AddNumber method and //passing 10 and // 20 as the parameter list int value=cal.AddNumber(10, 20); Console.WriteLine("The result is {0}", value); Console.ReadLine(); } } NIIT Encapsulation and Abstraction 4.15 The preceding example begins at the start of the Main() method of the Calculator class An object... itself NIIT Encapsulation and Abstraction 4.17 The output of the preceding code is as follows Output of the Recursive Method Program Using Methods with Parameters As discussed earlier, parameters allow information to be passed in and out of a method When you define a method, you can include a list of parameters in parentheses Declaring Methods with Parameters Each parameter has a type and a name You . Use static variables and static functions Objectives Encapsulation and Abstraction 4.3 ¤NIIT Abstraction and encapsulation are important features of any OOPs language. Abstraction involves. information to be visible. Introducing Abstraction and Encapsulation Defining Abstraction Defining Encapsulation 4.4 Encapsulation and Abstraction ¤NIIT An access specifier defines the scope. chapter also discusses the static variables and static functions. In this chapter, you will learn to:  Define abstraction and encapsulation  Implement encapsulation by using access specifiers
- Xem thêm -

Xem thêm: Encapsulation and Abstraction ppt, Encapsulation and Abstraction ppt, Encapsulation and Abstraction ppt