0% found this document useful (0 votes)
30 views80 pages

Chap 12 13

Uploaded by

mr.arjunb27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
30 views80 pages

Chap 12 13

Uploaded by

mr.arjunb27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 80
12 Object-Oriented Programming io AT ance ca Encapsulation Inheritance Polymorphism Abstraction Sef sgn Interfaces Pe ee Cagis 82 engiocers are given specialize tools and are told to sen a situation where sce eines ar? Q ona ato de de to ponvavadabty of any proper model or design, Simi or ee developement alsa # metel anu a proper design are needed to develop ant Pa ieee tev pe of programming medels followed while developing a softwere cee ae (nent Programming (PUP) and Objet Oriented Programming (OOP), ve bandon the concept of breaking @ problem inky modules, solving each module he Canepa soivel mcs wchve te ence problem, A module can be a mrthaa gt aaa 24 ae te te de FOP moded, you can call one method from another. This implies that thee soled “Krsonent on each other: thereby. making the reusability of code difficult. The languages that ae den CORD, FORTRAN. arn C Made ‘he mal of COP ha en iret’ to overcome the dificuly of limited or no reusability of code, the comp flames ants to reuse the existing code. A class acts as a blueprint or template lomtances oe abycts Thus Nueprint oF template describes the state and behavior for all the objects of ihn The behaviors and properties of objects ae represented by methods and variables, respectively Is «an also create interfaces that provide the ways of interactions between objects with the outside world Ay setae 2 collection of methods that have empty bodies. Amongst these two (POP and OOF) models, Ooh commen asthe best oe to follow since it allows an approach, which is related to eal world objects, tn tes chapter. you lear about the features of OOPS, such as encapsulation, inheritance, polymorphism, and attraction. You also ear about interface, sealed classes, sealed methods, and extension methods, Lt’ start by learning about encapsulation lation Jaton is the process of hiding the irrelevant information and showing only the relevant information ofa spect obec to mer Let's try to understand the concept of encapsulation with an example. When a customer fm fe purchase 2 refrigerator, the customer looks for the factors, such as color of the refrigerator, is ‘penctionalities, and storage capacity; whereas, it's internal working and wiring system are hidden from the ‘catemer The company does not want the customer to tamper with the wiring system; as a result, it keeps the ‘detals of internal wiring system hidden from the customer. This process of hiding the internal facts is known as ercapwalanon ln terms of OOF, encapsulation isthe process of wrapping up data and members of a class. Its an approach af hosting the ttermal state and behavior of a class or an object from unauthorized access. Encapsulation restricts ‘ssers ftom sharing and manipulating data; thereby, minimizing the chances of data corruption, The advantages of speapralation areas follows 4 Cr 4 av protect our data from unauthorized access. For this, instead of defining our data = ce Foe heels (euch as data members, member function, properties, oF indexes) Frovaat J private data can indirectly be operated in two ways, firstly through the aceessors and mut snd secondly, through the named property {Pcreanes the maintainability of the code by showing only the relevant information toa User. fore o sits corruption by enabling private member variables of a class to be accessed through methods or properties Binds member variables and functions of a class into a single unit. This is also called wrapping up of 42 members and member functions in a class, ee ed Object-Oriented Programming encapsulation Using Accessors and Mutators Ta save our precious data from unauthorized access and corruption, declare it with the pepe evar let's ereate a new console application, names| ERP SY {also available in the CD) to e ceessors and mutators, Accessors of the Program.cs file of the Employ’ ng a ble, Replace the default code ing 12.1 Listing 12.1: Showing the Code of the Employes Application ising system: using SYstem.collections. Generic: Using system. Ling; Using system.Texts namespace Enployee { public class Employeedetail { private string Name; 17 accessor} U pubic sering gett return Name; ) // mutator public void set(string name) { Name = name; ; } ) public class Mainclass { static void Main(stringL] args) ( 5 Emplayeebetail detail = new Employeedetai] (); detait.set("Martin”); ergata writeLineC’The Employee Name is :” + detail.getO); Console.write("\nPress ENTER to quit..."); console-ReadLine() y y In Listing 12.1, we have defined tw: Name variable. The get() method accessor, displays the Figure 12.1 shows the output of Listing 12.1: ‘0 methods set() and get(). The set() method mutator, sets the valve of the value of the Name variable on the Command Prompt Figure 12.1: Showing the Output of the Employee Application Encapsulation Using Properties In C#, you can also implement encapsulation by using the us pair of get and set methods, Let's create an application named how to implement encapsulation using properties. Listing 12.2 shows the code of the S Listing 12.2: Showing the Code of the student Application using system; Using system-col lections.Generic: Using system-Li USing System. Tex Namespace Student { public class Studentbetail { private string Name; public string StudentNane ( get { a defined properties, These properties contain a (also available in the CD) that shows application: return Name; 437 i ser ( ) name = value; ) ) ig class mataclass { Pe etic static void main(string(] args) { Stidentoetarl detail = new studentoetail Q; Se detart stadentAane = * waren"; f Gonsole-weiteLine (The Student Name is :(0)", detail seu Console. writeC"\npress ENTER to quit identiame) Consale Readtined) ; ) ’ , have declared a named property St in which the get.() and set () acacia the Name variable. =a Figure 122 shows the Listing 122 Figure 122: Showing the Output of the Student Application Inheritance The most important reason to use OOP is to promote reusability of code and eliminate the redundant code. To reduce ve object oriented languages support inheritance. (Inheritance is the property through which a class d wes properties from another class. A class that inherits the properties of another class is called a = denived class; whereas, the class from which the child class inherits properties is known as a parent or jsss. A parent class is at a higher level in the class hierarchy. A class hierarchy defines the logical ucturing ofthe classes, such that a general class is on the top of the class hierarchy and more specialized Lasse ate at the lower levels, For example, the Animal class can be a base class for a number of derived classes such as Dog, Cow. and Tiger Inherita § sr types, which areas follows: Sinple inheritance —Refers to inheritance in which there is only one base class and one derived class. This means that a derived clas inherits properties from single base class. 3 Hierarchical inheritance —Refers to inheritance in which multiple derived classes are inherited from the same base clase © Multtevel inheritance — 4 eet Refers to inheritance in which a child class is derived from a class, which in turn class, o, Nultiple inheritance Refers to inheritance in which a child class is derived from rmultipe base classes Support realinet rarchical and multilevel inheritance because there is only a single base class. It does Po! 1po Pic inbentance directly. To implement multiple inheritance, you need to use interfaces. ‘An interface is @ collection of data ‘member functions. You leam more about intertoree i The class which allows inheritance of i ts common ‘and the class that inherits the properties of base class is known as a deme mown a a base or parent class ane 7 cassis the parent class and Derived nae, Naw” a8 a derived or child class. In Listing 123, the BaseCla°s Oj “S88 Glass is inheriting the features of BaseCass class therefore, itis the 438 ae Object-Oriented Programming Let’s create an application named MyInh (also available in the CD) to learn hh fo to inherit» «Hee Listing 12.3 shows the code of the MyInhex application: Listing 12.3: Showing the Code of the using system: using gystem.collections. Generic; Using system.Ling; Using System. Text; nanespace Myinheritance { public class Baseclass { public int DataMenber; public void BaseclassMethod() { ‘Console writeLine("T am a BaseClassMethod()") ; } ) public class Derivedclass Baseclass {public void verivedclassmethodO { Console.writeline("I am a DerivedClassMethod()"); ) ) public class Program { z public static void Main(string{] args) { // Create a Base Class Object Console.writeLine("I am accessing Base Class object: Baseclass bc = new BaseClass(); be.Datamenber = 1; be BaseclassMethod() ; // Create a Derived Class object Console.writetine("™"); Console. writeLine("I am accessing Derived Class object Derivedclass de = new Derivedclass(; dc.DataMember dc.gaseclassMethod() ; dc.Derivedclassmethod ; Console.write("\nPress ENTER to quit.. F Console ReadLineQ; ? } In Listing 123, we have created three classes, 5 Deriv and The iv ass class. This implies that the DerivedClass class inherits all ass class, In the Program class, we have initialized these classes and invoke their Class class inherits the Ba the members of the Basi methods, Figure 12.3 shows the output of Listing 12.3 Figure 12.3: Showing the Output of the Myinheritance Application 'm this section, you learn about the following topics in the context of inheritance: Inheritance and constructors @ Sealed classes and sealed methods Q Extension methods 439 — —_._ Lets start with inheritance and constructors, and Constructors a tt isa special method of a class, which is used to initialize the jo A contrat ale by dealt whenever an objet ofa class is created. Its ie Ged cou comma bark tae costes Ts haba clas AT Tea classes stot When ys tae a derive ls, the constructor of the hse lass mot mney weve. the dealt orto the ase clas calle automatically and then the deviney cali he wa the casrostor of the ase cas niles the members ofthe base class bee aorta ets oka Using 124 hal shows an example explain eg Comers ssi class is derived from the BaseClass class and the SubClass2 class from the Sesclasei lass. Each class has its constructor definition, Therefore, when the SubClass? ¢lass is ‘instantiated, first the default constructor of the BaseClass class is called, then the constmctor of the SubClass class is called, and at last, the constructor of the SubClass? class is called, Sealed Classes and Sealed Methods Sealed classes ae classes that cannot be inherited. You can use the sealed keyword to define a class asa sealed ‘lass. The syntax of declaring a sealed class is a follows: error message, as shown in Figure 124 You will get an error message, as sh . Jo 1 Wysutecin Derves eet dere trom seed Pe tiyssiedCishiyclse Figure 124; Showing the Error Message aftr Inheriting a Sealed Class wd class can contain sealed methods. Similar to the sealed cls sealed methods are also defined using, i seuerived clase cannot override the sealed methods; however, you can use a sealed method eval method with the same signature. It means that in methods, you always use keyword, as shown in the following code snippet: A sei the sealed keyword. to override an inherited vi + keyword with the combination of override class Baseciass { ass tic virtual void seatedMethod© { ) % ass perivedclass:saseclass cast Re sealed override void SeaTedwethod© / {method Body -//method Body i Here, the sealed method SealedMethod() overrides the virtual method Se=% ere ine eeiags. Any derived class of DerivedClass class cannot further override the method. Now, le’s create an application named MySealedClass (also available in the CD) that shows how a class can be declared as sealed, Listing 12.5 shows,the code of the MySealedClass application: Listing 12.5: Showing the Code of the MySealedClass Application using system: using system.collections Generic; using system.Ling: sing System. Text; namespace MySealedclass { sealed class MyClass { string fNane; string INamé ‘int Age: public void Getvetail@ { 2 B Console.write(’enter Your First Name: ‘fwame = Console. ReadLine(); Console.write("Enter Your Last Name:") ‘Wane = Console. Readtine(; Console.write("enter Your Age Age = int.Parse(Console.ReadLine()); defined in z public void shonbetail( { . ‘Console.writeLine(fiame +" " +1Name +", you are " sage +” Years old ? JJ Foliowing Vines shows compiler error as Sealed class cannot be inherited 74 class perived : wyClass / Class mainclass ( static void ain(string{] args) ( yclass. obj = new MyClassQ; obj .cetvetailO: word. This take the input fom a user and show the det ass in the Main) method of the MainCleas Detail) method extend a class without creating a new derived class or od, but is invoked with an instance of the extended class. nethod which uses the this keyword be re its first parameter. Only a the this keyword in the first parameter of a static method can use wt an example of extension method nt MyExtensionwethod(this string Number) psi ty static ine mstaticuethod(string mutter) method tody | 1 ( string maber = “100 tot ett = mmr myexvensfoonthod 1) Line » ) IM SAE = MyClass.mystaticnethod (wumber); —7/ Line @ tensionMethod() method is an extension method that by default uses the xt variat d and a static method are as follows: Jo not oer neth th Keyword before the first argument; whereas, static methods dé contain th keyword argument declaration. Line ) When an extension method is called, the argument declared with the this keyword not naeee | Pet), whereas, while calling a static method, you must pass all the Be are af defined in a static class only, but itis not necessary that the static method are ina stat , how 0 we Now, let's create an application named 4 (also available in the CD) to lear b — setng, 126 shows the code of the My Ext 4 application Latin 126: Showing the Code of theMyExtenstenitethiod Applicat using system using system. collections.Generi¢; ising system. Ling; Using system. Text Wenegpace MyextensfonMethod { public static class MyClass { return Int32.Parse(Nunber) ; } fublic static int MystaticMethod(string Number) { return Int32,Parse(Nunber) ; } y Class Mainclass { static void Main(string(] args) { ‘string Number = "100" GBhsole.writeLine("The Output from Myextensionsethod()” console.WriteLine(ext) Console.writeLine(""); Console.writeLine("The output from MystaticuethodO Console.writeLine(stat); Console.write("\nPress ENTER to quit. Console.ReadLineQ ; } y y In Listing 12.6, we have created two methods, MyExtensionMethod() and ¥ d(), The xtenziontiethod() method is an extension method, which has the this keyword before its string fyPe argument, Number; whereas, the MyStaticMethod () static method does not have the this keyword ins Srgument declaration, While calling the MyExtensionMethod () method, we have not passed any avEuneTE (cee Line A of Listing 126); whereas, in MyStaticttethod () method calling, we have passed the Number argument (see Line B of Listing 12.6). Figure 12.6 shows the output of Listing 12.6: Figure 12.6: Showing the Output of the MyExtensionMethod Application snow learn about polymorphism: Polymorphism Polymorphism is one ofthe important features of OOP that is used to exhibit diferent forms of any EBS rocedure, With the help of polymorphism, you can use one procedure eT Sears Ren a ce ‘or example, you can make a procedure for calculating the area of a geometrical figure and can ail ofa circle, triangle, or rectangle using the same procedure with different parameters for ‘each geometrical figure The advantages of polymorphism are as follows rence during runtime igh the same name 2 Allows you to invoke methods of a derived class through base class refe © Provides different implementations of methods in a class that are called throu est —— ome i x mom snes pete. fst wwe mae to Kenow that an object of a derive class can Mae cane chee ernie ce ers Oe Bae San a, ee NE Sa tee oa «Moe e the Hane ss Glam ss haiding an cbyet (b=) of type Deri vedClass clam. tn thie om we am taking he tec the Der oest less Gam as an ctqect of the BaseClass) ‘This possible Case ee te oe 2 comer, winch ae a lew 2 ce te eee ceri cer permet orertoating 2 Treen sete , and for < Is overloaded then [= must aso bo nd > \When you overload an operator, you need to create a method that must be preceded by the operator keyword, Dverloading of a unary operator is known as unary operator overloading and overloading of a binary operator 'snown as binary operator overloading, Let's create two applications, UnaryOperatorOverload and BinaryOperatorOverload (also available 1 the CD), to learn how to overload the unary and binary operators, respectively. Listing 129 shows the code of the 124 application: Listing 129: Showing the Code of the Un using system; sing system.collections Generic; using Systes.Ling; using Syster. Text; namespace UnaryOperatoroverload { class unaryoperator { private int number; private int umber2; 2 publ ic UnaryOperator() } public Unaryoperator(int number, int number2) { i Nurberl = nunber1; Nunber2 = nunber2: verload Application Public void showataQ) { erie 2) : Console.WriteLine("The Nunbers are: " sNumber1 +" and " +Number?) public static unaryoperator operator. -(Unaryoperaton"0PF) UnaryOperator obj = new Unaryoperator(); 0bj.Mumberl = -opr.Nunber obj.Nunber2 = -opr Number? return obj; ’ ) class mainclass ( public static void main() { Unaryoperator opr = new Unaryoperator (20, 30): Console. wri tet ine("Be: jer] "D5 . opr. shonoatagy;« ™"9"* Operator, overloadinay] pee 6 SE ae emo 2. __ Object-Oriented Programming Unaryoperator opr2 = new Unaryoperator() a opr2 = -oprl; Console.WriteLine¢” +} Console.WriteLine("after Operator overloading"); opr2.showbata(); Console.write("\nPress ENTER to quit..."); Console ReadLine(); } } in Listing 129, we have created a class, UnaryOperator, which contains a constructor, UnaryOperator, In jarizeits two variables, The UnaryOperator class also contains the ShowData() method to display the value of vsclacs variables and overload the functionality of the - (minus) operator. The - operator is overloaded by using ne operator keyword, Next, in the Main() method of the MainClass class, the - operator is used to show the ‘exative value of an object of the UnaryOperator class Figure 12.8 shows the output of Listing 12.9: Figure 12: showing the Output of the UnaryOperatorOverload Application Listing 12.10 shows the code of the BinaryOperatorOverload application’ Listing 12.10: Showing the Code of the BinaryOperato: using System; using system. collections.Generic; using System-Ling; using system. Text; namespace BinaryOperatoroverload { class BinaryOperator { private int Number1; private int Nunber2; public einaryoperatar® exload Application Public BinaryoperatorCint numberi, int number2) { Numberi = numbers Nunber2 = number2; } Public void showoata() { Console.writeLine("The Numbers are: “+Numberi +" and "+ Nunber2) } t ssemmNRENNRR NEE ERO TTT Binaryoperator opr = new Binaryoperator Qj; opr.Number1 = oprl.Nunberl + opr2.Number1; opr.Number2 = opri.Nunber2 + dpr2-Nunber2; f return opr; y Class mainclass ( public static void main) { Binaryoperator oprl = new Ginaryoperator (20,30) oprl.Showata(); // displays 20 & 30 BinaryOperator opr2 = new Binaryoperator (30,40)i opr2.showoata(); // displays 30 & 40 Binaryoperator opr3 = new Binaryoperator Oi 447 i eee 70 r} showoatac); // distplays 50 & Seaswte write(\nPress ENTER to quit.. Console, Read the? ) ; d Stere peed «dass BraryOperrs, which conine « const eet ame Sam ype lt also contains the Sow Data) method to display rea ute foe ves he unto of the + (akdtion) operator, The + operator i oveoaden tt , : ee ee weyoriei ian ne Figure 12.9: Showing the Output of the BinaryOperatorOverload Application Indexer Overtoading ei to treat an object as an array. It is used to provide index to an object to obtain values eenting an indexer requires you to use brackets ([ ]) with an object to get and set a value es, with the difference that in case of indexers, you do not need to ne t© them. You need to use the this keyword to define an indexer, eclared as proper ppet shows how to define an indexer PHIIC string thisL[int Position} { wet ( 1 SBR Mreacalrositton); set ( y MPmalrosition) = value; pet. the get property is used to retrieve the index of the MyData member, while the st index to the member. You can also see that there is no name assign to the indexer. Similar to ther data’ members, indexers can also be overloaded. Let's create an application named *© available in the CD) that shows how to overload an indexer. Listing 12.11 shows # application code of the Listing 12.11: Showing the Co using system; using System. collections.ceneric; sing Systen.Lina; using system. Tex namespace Indexeroverload ( Class tyclass ( private stringt) moat Private int arreysiee public MyClass(int size) ( Arraysize « size: Mybata = new string{size]; for (hot Tm 02 1a Shae! sea) 4 Myarali) = “patavalue"; of the ndexerOverload Application d public string thisLint Position] 448 Brass wainctass indexer 3] tyandexer (5) - MyIndexer (7] = indexer E console.writeLine("\ Console.writeLi Console.writetine("\ Nyindexer ("Have a 1 Console.write("\ Console. Readt ine! 1m Listing 12.11, we have overloaded indexers by passing different type of parameters, We have defined two indexers, with the int type and string type parameters, named Position and data, respectively. These Nidexers are used to display the values of different string data that is passed in the Main() method of the lainClass class. Figure 12.10 shows the output of Listing 12.11) 449 SSS Figure 12.10: Showing the Output of the IndexerOverload Application nism Oversiding lerived class to provide a specific implementation of ‘method that is werrides or replaces the feature known as runtime polymorphism because the tect during the execution of a program (runtime) instead of during the v the method defined in the derived clas is invoked and methou of a derived class that is already defined in petbea keyword : to override a method of a base class in a derived class lass sasecjass ( DaIic RIERA void Showoatac) { Method body wesclasstaseclass { : PONE GERM void Showoata() { method tody ) ) the 1ass, the 2.() method is marked class, the 2) method is marked with the * base class which can be overridden in a derived class to change 4 You can declare a function as virtual ina base class by using the vir od ma derived class, you need to use the override keyword in dere also available in the CD) shows an example © keywords, Listing 1212 shows the code Listing 12:2 Application using System; os using systes.collections ceneric; using System.Ling: using Systes.Text ame space Methodoverriding ( class Program { static void main(string(} args) ( 450 Object-Oriented Programming person p = new Person; p.setage (18) ; Rdultperson ap = new AdultPerson(); ap. setage (18) ; uf Console-writeLine("Person Age: {0)", p.getageQ): Console.writeLine("AdultPerson Age: (0)", ap.getageQ); Console write("\npress ENTER to quit..."); Console. ReadLine(); ) Jubtic class person { private int fage; public Person() { fage = 21; Jubtic virtual void serageCint age) ( fage = age: Jubii virtual int gerageO return Fage: d ) public class Adultperson : Person public adultperson() { } bverride public void setageCint age) x if (age > 21) base setage(age); ) ) Sal In Listing 12.12, we have created the Person and AdultPerson classes, where the AdultPerson class is the derived class of the Person class. The Person class contains two virtual functions, setAge and getAge. The AdultPerson «lass is overriding the setAge() method of the base class by using the override keyword. Figure 12.11 shows the output of Listing 12.12: Figure 12.11: Showing the Output of the MethodOverriding Application sets you want to derive a class from a base class and to redefine some methods contained in this base class. iP case, you cannot declare the base class method as virtual. Then how can you override a method “ hout declaring that method as virtual in the base class? This can be possible with the new operator. The The cberater is used to override the base class method in the derived class without using the virtual keyword. new operator tells the compiler that the derived class method hides the base class method. Let's create an application Het wate af application named YethodHiicing (also available in the CD) that shows how the derived class a od je the base class method using the new keyword. Listing 12.13 shows the code of the hodiiiding applicator Listing 12.13: Showing the Cod using systems using System.collections Generic; using system:Lings: Using system. Text: anespace Methodiiding ( Class waseclass odHiding Applica’ Chapter 12 = = ee ubtie void mywethed© ; public vOdnsove.writecine("E am in Base Class ) Dass perivedclass + gaseclass ( console.writeLine("I am in Derived Class"); } ) lass mainclass { static void Main(string[] args) { faseClass be = new BaseClass (); perivedclass dc = new Derivedclass() ; be.Mymethod dc.mymethod ; be'= new derivedclass 0; be.mymethod(; //saseclass Method Console.write("\nPress ENTER to quit... Console .ReadLine(); ) y In Listing 12:13, we have overloaded the tooverride the Myttethod () method of the Basec ivedclass class operator in the MyMethod () method of the De: Figure 12:12 shows the output of Listing 12.13: Figure 12.12: Showing the Output of the MethodHiding Application Let's now learn about abstraction, Abstraction Abstraction ithe pivesss of hiding the details ofa particular concept or abject from a user and exposing only the Understand the conn onceP's of abstraction and encapsulation are complementary to each other. You cit Ae yous aa enteP of abstraction well with the help of the example discussed in the Encapsulation st ‘A pat hae seni the example of refigeator, when a cuter gous to purchase a ez HE does not devenbe the fa sciPtion of the features of refrigerator, such as the color and storage capaci ese eee ier working system of the refrigerator. The process of showing the B&r%) aaa 'Seratoris abstraction and hiding the complex information from the user * © In terms of abstraction refer pa io se ola ieee vee er the got representing essential features without including the bockgrt functionality, inst maection is the development of classes, objects, and types in terms 0! fmt edo hc tenn Sa a oat oot (ns et 0c pe \Thatata haters Cet eae eae Managing the complexity of the code Decomposing complex system into smaller components {Let's eam about the abstract classes and methods inden 452 Tae eee. Object-Oriented Programming Classes Aba can have a single base class and multiple derived classes. If you do not want that any class can create In Ch, yo sae class, you can make the base class a abstract. The abstract Keyword ina clas indicates an ob Meant be instantiated. You can create the instanceof its derived class (only if not marked as Tet cg camo cee Listing 12.14: Creating an Abstract Class { ypata Menbers and Menber Functions paseclass 2yass verivedclas: _// vata Menbers and Member Functions: dias wainclassO t seclass bc; /{can"t be instantiated safivedclass de; //Can be instantiated = , oe In Listing 12:14, we cannot instantiate the Bas=C1.ass class because we have declared itas abstract ‘Some characteristics of an abstract class are as follows: @ Restricts instantiation, implying that you cannot create an object of an abstract class Allows you to define abstract as well as non-abstract members in Requires at least one abstract method in it Restricts the use of sealed keyword in it Possesses public access specifier; therefore, it can be used anywhere in a program, Abstract Methods An abstract method is similar to a virtual method which does not provide any abstract method does not have method body. It can be declared by using the abst coule snippet shows how to create an abstract method: public aBSERAEE void AreaCint Length, int Breadth) ;) "hill Some characteristics of an abstract method are as follows: Restricts its implementation in an abstract class Allows implementation in a non-abstract derived class 2 Requires declaration in an abstract class only Restricts declaration with stat ic and virtual keywords Allows you to override a virtual method Listing 12.15 shows the implementation of an abstract method: Listing 12.15: Implementing an Abstract Method qublic abstract class shape opoo ooooa public ‘abstract void area int Gs (ee Area() can't be 453 Chapter 12 ’ public class Rectangle: Gastcshape ( override void AreaCint Length, int areadth) ( "placed reat) can be taplenented at UME place ; in Lasting, that the method wan abst S, you can see that the Area () method is preceded by the ract metho! obstract keyword, which speiteg Let's now learn about interfaces Interfaces An interface is a collection of data members and member functions, but it does not in are introduced to provide the feature of multiple inheritance to classes. Multiple OOP which allows @ class to inherit from multiple classes. The methods define: plementation, they only specity the parameters that they will take and the ty; interface is always implemented in a class. The class that implements the members of the interface mplement them. Interfaces inheritance is the feature of ud in an interface do not have pes of values they will return. An interlace needs to implement all the Jn, interfaces are more flexible in their implementation, than in any other lang ‘equivalent of an abstract base class. This implies that you cannot instantiate you can olfer a set of functionality to classes that implen modifiers as a class, such as public and privat of declaring and implementing interfaces in C# Syntax of interfaces ge. An interface in CH is the aan object through an interface, but the interface, An interface can have the same access Now, you learn about the following concepts in the context. Implementation of interfaces Interfaces and inheritance Let's start with syntax of interfaces Syntax of Interfaces An interface is declared just as a class, but the only difference is that a class is declared using the class Keyword: whereas, an interface is declared using the interface keyword. Interfaces behave as templates that } have method declaration in them. These methods are abstract in nature, as they do not have code in their body, ‘s dsussed class that implements an interface must implement al of its methods; otherwise, an error occurs You can declare an interface using the following syntax: [rrerface » (A*TAck method Declarations in interface Body The interface definition itself con the methods is interface jon of we ne code, only the signatures of the actual method. The implementation © Gt t the class that inherits the interface. Listing 12.16 shows the example of creating Glearly, the Chasinel interface has face has two abst ineracehs two aurct method an 2 ‘etum any value. In this ase, any inheriting the Book act methods named Next (), and Previous () oe ido not 1 U-and chapter (). All of these methods are void ang £1 ‘lass can implement the methods ofthe interfaces Channe: an a Object-Oriented Programming Implementation of Interfaces “plement multiple inheritance in a program, you need to use interfaces. Implementing an interface is similar Fe eye a class. Let's create an application named Accessingiaterface (also available inthe CD) that (one plement an interface in a class. Listing 12.17 shows the code of the AngInterface shows how to i plication: using System colTections Generic; namespace accessingInterface . public interface Channel void Next; void Previous(); ) public interface Book { void NextQ; void chapterO; Crass: Programeichannel Wook // inplenenting Interface { eS void channel.Next() { Console.writeLine("channel Next"); i void Book.Next@ { Console.WriteLine("Sook Next"); } public void Previous) { Console.writeLine("Previous"); ) public void chapter) { } Cori writeLine("Chapter”: geatic Shae ring] args) Program app = new Program() @ook)app) .NextO ; app . Previous (; app.chapter() Console.write("\nPress ENTER Console. Readt ine(); ¢ } } 'n Listing 12.17, the Program class implements the interfaces named Channel and Book. The object of the =ogram class calls the method that belongs to an interface. Figure 12.13 shows the output of Listing 12.17: raptor 12 —____ odvdet ha titlae, You cen inhinine sa obect of he Interface hy type cating th sett hese Fagepuscies KOGAN A Gabel nthe le ea You on cE ces 10 support the concept ‘ance (also available in th Listing 1218 cave the code af the can inherit another interface shows. the Application using Syston: Ghing Syaten.collections Generic; Using syaten. Ling: ing systen. Yen runenoace Interfacermheritance ( ‘interface Basetnterface ( void GetPersonalpetai!(); void Getcontactoetail(; void Showoerai1O; lass Interfacermplenenter : perivedinterface { ‘string Nase; tae age; string address: long Phonenuaber'; Public void GetPersonaloetail() { Console. write("Enter Your Name: Nane = Console.ReadLine() ; Console.write("enter Your Age:"); Age = int.Parse(Console.ReadLine()) ; public void cercontactoerail() { Console.write("Enter Your address: address= Console.Readt ine(); Console.write("Enter Your Phone Number A +r = Tong.Parse(Console.ReadLine() Public void ShomoerailO { Consale.writeLine ) ) lass mainclass ( static void wain(string() args) { waeertacelmolenenter wyobj = new Interfacermplenenter( at) cetrersonaloetattO; Getcontactoetat(); ‘y0b) ‘showbetaslos Gonsole.write("\nPress ENTER to quit.. f east ined): 456 ee Programming ; interface is inherited by the 4interface interface. Then, the Interfacelmplementer ae Figure 12.14: Showing the Output of the Interfaceinheritance Application Lets now summarize the main points of this chapter. Summary In this chapter, you have learned about OOP and its features, such as encapsulation, inheritance, polymorphism, and abstraction. You have also learned how to create a derived class from as base class and how to overload an ‘operator, and a method. Finally, you have learned about interfaces, such as how to create, implement, and inherit an interface. In the next chapter, you learn about pointers, delegates, and events, Quick Revise Ql. What is Object Oriented Programming? Ans. Object Oriented Programming (OP) is a technique to develop logical modules, ‘such as classes which contain properties, methods, fields and events. Q2. What is a class? Ans. Class is the elementary template for developing software programs in Object Oriented Programming: Classes are developed in all Object Oriented Programming language to represent real world, entities. For, example independent classes are developed for unique entities such as, student, aircraft, book, flower, car, and innumerable other objects that exist in real world. 3. Define the objectives of abstract class. ‘ans, Abstract class isa prime technique for using abstraction in Programs that are developed by using any’ Object Oriented Programming language. It is a special Kind of class that contains at least one abstract method. Abstract method is declared for defining an abstract behavior of an entity: a Mention the differences between abstract class and interface. The differences between an abstract class and an interface are listed in the following table: Abstract. mae A class can extend only one abstract class A derived class that uses abstract methods of an abstract class must override all abstract methods. However, in ease ‘of non-abstract methods of an abstract class, it is not ‘mandatory for the derived class to implement all of them plements an interface must vPimnethods defined by the | | Any class can extend an abstract class Only an interface can extend another in i ee ee - Chapter 12 SE a. \ An g Ans os. Ans Ans to. Ans. meant by data encapsulation? eae a fin pint wrapping up of data and members ina class, Only 4 rpuagusinatha octet ina piv wets 616 GARR TA GGe2 WECal crcapsulation ee hue the internal state and behavior of a class or an object from unauthorized . Want manipulating data, thereby minimizing the chances ternal user trom sh What is data abstraction? on Js the prowess of hiding the details and exposing only’ the essential feat particular concept or byt. is the development of classes, objets types in terms of te stead th implementation detalls ARstaction simply denotes a model, a view, ang h for an actual item (class object. ot type). Presentation, Define the term inheritance. Inheritance is the property through which a child class obtains all the fe class. A parent class is one which is at a higher level in the class hierarch ass inherits the common properties of another class, the class inher serve class an the clas which allows inheritance ofits common proper Why the virtual keyword is used in code? The virtual keyword is used in code for defining methods and the derived classes Dota abstr y than the ld Hing the properties ica ties is called a base class, =e Properties that can be overridden in How is method overriding different from method overloading? When you override a method, only the behavior of the method is chan, ged for derived class. On the otherhand, overioaing a method means defining another method with th re same name within the class, What are the different ways a method can be overloaded? A method can be overloaded: 2 By varying the numbers of parameters 2 lthe parameters are same, then using different data ty pes for the parameters 2 By using different sequence of the parameters -_ — 13 Pointers, Delegates, and Events Chapter 13 “< Pointers, delegates, and event-handling sy ns are othe most important features of C4. A pointe ig g another datatype, such as int and char. Pointer variables are declaged ayes a type that references a method. After a method hay beet te, the delegate behave hod. ‘The delegate keyword is used iq legate in Caras similar to a function pointer in C or C++, Delegates can also be used to erent en events An event is a degate type class member that is used by an objector a clas to provide's that holds the memory addres dereference operator (*). A d similar to the ass notification Wo other objets that an event has occurred. An event can be declared with the help of the evans keywor! tn this chapter. you learn abwout pointers and theie declaration. You also learn how to perform various operatio, on them. Apart from pointers, you also learn about deleg xl how they are declared, instantiated, and invoked. You a anonymous methods. Finally, you lear about the vepts of events in C#, such as event source, event handlers, and multiple event handlers, Pointers \ pointer is a memory variable that holds the address of another variable. Pointers are widely used in Procedural programming languages, such as C, You can use pointers where execution speed of the program i highly important asi allows you to write the low-level code very fast. To maintain the type safety ae! security ofthe program, you must compile the program with the vnsae keyword at the Command Prompt Moreore, the pointers must appear in the section of code that is marked by the unsafe keyword. The cade, which G marked as unsafe: runs outside the control of Common Language Runtime (CLR). Let's now leary aboct declaring unsafe code, declaring pointers, performing arithmetic operations on pointers, and converting pointers. Declaring Unsafe Code fuinters are not supported in C# inherently; however, they can be used in the unsafe code, which is the code tha, has been marked as unsafe. You can mark a piece of your program code as unsafe by creating a block using the Keyword and putting that code inside the unsafe block. Additionally, you ean also mark frustures, classes, and type members (variables or methods) as unsafe by using the unsafe keyword in their lcclarstions. By default, CLR checks the program code for type safety. A piece of program code is considered to be type safe if itis accessing other pieces of code using only interfaces, Therefore, if your program contains some lth aig as been marked as unsafe, the C# compiler does not compile your program code until you explicitly tell the C# compiler to skip the type-safety checking. One way to skip the type-safety checking is ¥o use the C# Sgiimand-line compiler utility, csc. exe, to compile the C# source code file and specify the /unsafe keyword while compiling the C# source code file. Consider the following code snippet to learn the implementation of the afe keyword in a Cé program: unsafe { .0 learn about covariance, contravariance, and inel] x = new int(10}; , int "px = ax; In the preceding code snippet, an unsafe block is defined that allows you to assign a pointer to an array. Let's consider another code snippet that allows you to define a pointer to an array’ unsafe int *x = new int(10}; ae In the preceding code snippet, an integer pointer (int _*x) is not an array; therefore, you cannot assign an siTaY to it. You cannot delete an array; therefore, it should be garbage collected Sometimes, you need to create a pointer to call an external function (which is external to a class). The Poe with calling an external function through a pointer is that the pointer points to a block of memory, which can garbage collected or moved in memory. In such cases, C# provides the £ixed statement that allows you to pina pointer in memory until you call the specified external function. The following code snippet shows how to use the fixed statement EE a ____Pointers, Delegates, end Events unsafe sto new int {iO}; fxeacint *p = &) {car iarunctionwthapointer (*p); y ) as you cant gee Inte preceding code snippet, the £4 xed keyword pins the pointer in memory until yo call the ne jnwthaPointer () function, Fixing a pointer is a temporary step, as you cannot fix a pointes in er pe lock stays in place only between the starting and closing braces of the block, which i= the fixed keyword. jyrrounded by peclaring Pointers .w that pointer isa variable that holds the memory: ‘address of another variable. In C#, you can declare As you knot As yovts to hold the memory address of value tyes: such as int, char, or double. The syntax for pointers Feclaration is as follows: ype> < de=reFerence: operator > _ STONES ressions used in the preceding syntax is as follows: a valu ue data type, such as int, char, or double. e-reference operator—Specifies the compiler that the variable succeeding this operator is 3 pointer “ariable, It is denoted by the asterisk(*) symbol. pointer name—Specifis the name ofthe pointer variable: co’ now take an example to know how to declare a pointer variable int *wypointer Be The preceding declaration sets up a poi ara integer type. The syntax *MyPointer refers tothe type located 2 the memory the MyPointer variable. Therefore, we can assi smypointer=100 t In the preceding code snippet, the *MyPointer pointer seen the starting four bytes of the memory address where the inteper value 100 is stored, Another important se bol used with the context of pointers is the & operator. It returms the memo ‘address of the variable that eee esThe following code snippet shows you to store the address of the variable through pointers: ‘int Nunber=1005 seg : int *myPointer mypointer=8Nunbers i From the preceding code, we can conclude that the MyPoin value of the Number variable is stored and *MyFointer is an by themyPointer variable. Pointers can also point to the elements of an array, as shown in the following code snippet ‘int *nypointers a ‘int Myaarray[50]} MyPointer=myarray[20] In the preceding code snippet, the MyPointex ‘variable points to the twenty-first (the array index starts from 0). rhe description of the expr type Specifies the val one inter variable named as MyPointer, which points tothe memory address location, which is held by 0 eu Se variable does not point tothe integer value 100; infact sr variable holds the memory addres where the Steger value located a the memory adress held create a Console application, named MyPointe® (also available in the: CD), which: of the int data type. Listing 131 hows the code of the Program.cs file ofthe #y# application: Listing 13.1: Creating Pointer of the int Data Type using system; " using system.colecti : using system-Lina! ee. emer ae oid maincstetngl) args) € | mar iets ae is eee ime ora ) S necethe value of ‘Number’ is: “+Number); Console writenineG The Vatie oF ‘myrointer” 1s!” «CintMyPotnter; Cea re gare to utes osee 5 , sn integer pointer MyPointer that holds the memory address ofan inegy Inecick the project name, which in this ease is MyPointer, in Solution Explorer and select th jes window appears, as shown in Figure 13.1 Ace torn) Te embed a custom maniet fat add Rt@ "ae Figure 13.1: Showing the MyPointer Properties Window 2. Select the tab in the MyPointer properties window ai oleae checkbox, as shown in Figure 13.2: 462 Figure 13.2: Selecting the Allow Unsafe Code Checkbox. Close the MyPointer properties window. Press the F5 key on the keyboard to run the MyZointer application. tion appears, as shown in Figure 133: The output of the MyPointer appli Figure 13.3: Showing the Output of the MyPointer Application You can also execute the applications containing pointers with the C# compiler. To do so, first you need to compile the program with the C# compiler (csc) along with the /unsafe keyword and then run the application at the Visual Studio 2010 Command Dereferencing Pointers Dereferencing a pointer means to access the value that is held by a pointer variable. Dereferencing of pointers done through the de-referencer operator (*). As the address operator () returns the address of a variable. the de-referencer operator (*) returns the value, which is on the memory address held by the («) operator. Lets create a Console application, named Dereference (also available in the CD), which shows how to dereference Pointers. Listing 13.2 shows the code of the Programs file of the Derefexence application: Listing 13.2: Dereferencing a Pointer using system using System.collections.Generic; Using System. Ling: using system. Text; hamespace Dereference { class Program { Z unsafe static void wain(stringl er13 int Number * 100; int® MyPointe Mypointer = Number; ii sre consoleswriveLine ("Old values:"); Konsole,writeLine("Nunber: "+ Number) ; Console.writeLine(NyPointer: "+ Cint)Mypointer); Console. writeLine("*MyPointer smypointer = 50; console. writeLine(’ Console-writeLine("New values:"); Console.writeLine(’Number: "+ Number) ; Console.writeLine('NyPointer: + *MyPointer) ; Dy + Gnt)myPointer) ; Console-WriteLinec"*MyPointer: " + *MyPointer); Console. Read); ) - ) In Listing 132 address held by &MyPointer. Change the settings in the Properties window of the Dereferer ‘you can see that the pointer variable *MyPointer holds the value, which is on the using the steps as performed in the ter application and run the application. Figure 134 shows the output of the preceding code: Figure 13.4: Dereferencing Pointers, ta Every time we execute the Dereference apol Using Pointers to Access Arrays In CH, you can acce pointers, Listing 133 shows the code of the Program.cs file of the Point Listing 13.3: Using Pointers to Access Arrays using System; Using systen-coTlections Generic; Using System. Ling: using system. Text: namespace PointerToarray { class wyclass ( public unsafe void Mywethod©) { 38e0) Myheray = new Ime (20); for Gint Counter = 0; Counter < 10; counters+) { Warray(Counter]'= Counter * Counter Fixed Cint* wypointer = inter = Myarray) F Showoata(hypointer); Bublic meate void showoaraCint® for'Gnei's ote tos try Cf Consoles writeLinets (pet +449): 464 fin, the value of pointer changes on the system. Array application: memory application to allow the unsafe code, by array elements by using pointers. Let's create a Console application, named ay (also available in the CD), which shows how to access the elements of an array by using } a Nass wainclass { : cieSpublic static void mainQ { ; wyclass myclass = new WyClassO: nyclass.mymethodO + Console riteC"Press ENTER to quit...) Console. ReadQ); } . . In Listing 13.3, we have created an integer array named MyArray[] and a pointer variable named MyPoinler through which we can access the elements of the MyArrayl] array. 3: Showing the Output of the PointerToArray Application Using Pointers to Access Structures ‘The pointers can be used with a structure if the structure contains only value types as its members, Pointers can access the members of a structure by using the pointer operator (~>).. Let's create a Console application, named PointersTostruct (also available in the CD), which shows how to use pointers to access structures. Listing 134 shows the code of the Programs file of the PointersToStcuct application: Listing 13.4: Using a Pointer for Accessing a Structure using) systen: = using system.coT namespace Pointerstostruct { struct Mystruct { Public double Length; public double Breadth; Public double Heigl public void Setpimensi Console.write(’ , Public void showve double volume console.Wri + lass mainclass { es Public unsafe static voi Mystruct mystruct = n MyStruct® mystructi = Chapter 13 Struct1->shonvol ume); sraesye arite tne C\N"): Console wr tere oprens ENTER to QUIT..." } “ ure named MyStruct and (->) operator is used to access its members the F3 key. Figure 13.6 shows the output of the preceding code: ee ee ree = : 136: Showing the Output ofthe PointersTostruct Appl Figur Using Pointers to a Pointer fe holds the address of another pointer variable. Let's Iso available in the CD), which shows how to use a pointer to point t ate a Console application, another of the Program.cs file of the r application: Listing 13.5: the Program.cs File using syst Using system. collections .Generic; using Systen.Ling using Systen. Text; namespace Pointerrorointer { Class Program { unsafe static void main(string{) args) { char Firstchar; char* Secondchar; Firstchar = 'S'i Secondchar = &Firstchar Thirdchar = &Secondchar; Console.writeLine("The value of Firstchar is: "+Firstchar); Console writeLinec’The Value of Secondchar is: {0}",Cint)secondchar); Console.writeLine(""The Value of Thirdchar is: {0} , Gnt) Thi rdchar) 5 console.writeLine("\n Console writeLine("Press ENTER to quit.. Console.Read(); } ) ) In Listing 135, we have declared a variable FistChar, a pointer variable SecondChar, and a pointer to & POISE variable ThirdChar ofthe char type. The SecondChar variable holds the memory address of the First mat variable and the ThirdChar variable holds the memory address of the pointer variable SecondChar. After running the application, the output appears as shown in Figure 13.7 fl chao NET | Fi ‘gure 13.7: Showing the Output of the PointerToPointer Application 466 )

You might also like