oops concepts

41
OOPs Concepts Chapter 6: OOPs Concepts Objectives This chapter explains Object-Oriented Programming concepts of C# in detail. At t this chapter delegate would be in a position to accomplish the following activities hat is a class! object and "ow to wor with them hat are constructors and "ow to wor with different t$pes of Constructors %xamining &tatic e$word hat are 'ethods! Parameter 'odifiers and %xplain different Parameter modifie hat is (nheritance and different forms of (nheritance hat is Pol$morphism and how to use )irtual and Override *e$words hat are &ealed Classes! Partial classes and (nner Classes hat are Abstract Classes and Abstract 'ethods hat is an (nterface and how to wor with (nterfaces

Upload: shivuhc

Post on 03-Nov-2015

221 views

Category:

Documents


0 download

DESCRIPTION

C

TRANSCRIPT

OOPs ConceptsChapter 6: OOPs ConceptsObjectivesThis chapter explains Object-Oriented Programming concepts of C# in detail. At the end of this chapter delegate would be in a position to accomplish the following activities. What is a class, object and How to work with them What are constructors and How to work with different types of Constructors Examining Static keyword What are Methods, Parameter Modifiers and Explain different Parameter modifiers What is Inheritance and different forms of Inheritance What is Polymorphism and how to use Virtual and Override Keywords What are Sealed Classes, Partial classes and Inner Classes What are Abstract Classes and Abstract Methods What is an Interface and how to work with Interfaces

IntroductionC# is a true object-oriented language and therefore the underlying structure of all C# programs is classes. As far as the .NET platform is concerned, the most fundamental programming construct is the class type. Anything we wish to represent in a C# program must be encapsulated in a class that defines the state and behavior of the basic program components known as objects. Classes create objects and object use method to communicate between them. This is known as object-oriented programming. The power of object-based languages such as C# is that by grouping data and related functionality in a class definition, you are able to model your software after entities in the real world. Classes provide a convenient approach for packing a group of logically related data items and functions that work on them. . Formally, a class is a user-defined type that is composed of field data (often called member variables) and members that operate on this data (such as constructors, properties, methods, events, and so forth). Collectively, the set of field data represents the state of a class instance (otherwise known as an object). In C#, the data items are called as fields and the functions are called as methods. Calling a specific method in an object is described as sending the object as a message. A class is essentially a description of how to construct an object that contains fields and methods. DEFINING A CLASSAs stated earlier, a class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, we can create variables of that type using declarations that are similar to the basic type declarations. In C#, these variables are termed as instances of classes, which are the actual objects. The basic form of a class definition is : Class classname{[Variable declaration;] [Methods declaration;]}

Adding Variables:Data is encapsulated in a class by placing data fields inside the vody of the class definition. These variables are called as instance variables because they are created whenever an object of the class is instantiated. We can declare the instance variables exactly in the same way as we declare local variables.class rectangle { int length; int width; }

The class rectangle contains two integer type instance variables. Remember that these variables are only declared and no storage space has been created in the memory. Instance variables are also known as member variables. Adding methods:A class with only data fields and without methods that operate on data has no life. The objects created by such a class cannot respond to any messages. We must therefore add methods that they are not necessary for manipulating the data contained in the class. Methods are declared inside the body of the class, usually after the declaration of instance of variables. We know that the general form of a method declaration is:Type method-name (parameter-list) { Method body; }

The body actually describes the operations to be performed on the data. Let us consider the rectangle class and add a method GetData() to it.class rectangle { int length; int width; public void GetData(int x, int y) { length = x; width = y; } }

The method has a return type void because it does not return any value. We pass two integer values to the method which are then assigned to the instance variables length and width. The GetData method is added to provide values to the instance variables.

Member Access Modifiers:One of the goals of object-oriented programming is data hiding. That is, a class may be designed to hide its members from outside accessibility. C# provides a set of access modifiers that can be used with members of a class to control their visibility to the outside users. The following sections describe all the visibility modifiers provided by C# and their visibility control. These modifiers are a part of C# keywords.Creating ObjectsAn object in C# is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred as instantiating the object. Objects in C# are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object. Objects must be allocated into memory using the new keyword. If you do not make use of the new keyword and attempt to make use of your class variable in a subsequent code statement, you will receive a compiler error. Here is an example of creating an object of type rectangle.Rectangle rect1;Rect1=new Rectangle();

The first statement declares a variable to hold the object reference and the second one actually assigns the object reference to the variable. The variable rect1 is now an object of the Rectangle class. Action statement Result Rectangle rect1 rect1

The method Rectangle() is the default constructor of the class. We can create any number of objects of Rectangle. Example:Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();

It is important to understand that each object has its own copy of the instance variables of its class. This means that any changes to the variables of one object will have no effect on the variables of another.Accessing Class Members:Now that we have created objects, each containing its own set of variables, we should assign values to these variables in order to use them in our program. Note that, all variables must be assigned values before they are used. Since we are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator as shown below:Object name. Variable name;Object name. Method name (parameter-list);

Here object name is the name of the object, variable name is the name of the instance variable inside the object that we wish to access, method-name is the name of the method that we wish to call, and parameter-list is a comma separated list of actual-values that must match in type and number with the parameter list of the method name declared in the class. namespace ClassExample1{ class rectangle { public int length, width; public void GetData(int x,int y) { length = x; width = y; } public int Rectarea() { int area = length * width; return area; } } class Program { static void Main(string[] args) { int area1, area2; rectangle rect1 = new rectangle(); rectangle rect2 = new rectangle(); rect1.length = 15; rect1.width = 10; area1=rect1.length*rect1.width; rect2.GetData(20, 12); area2 = rect2.Rectarea(); Console.WriteLine("Area1= " + area1); Console.WriteLine("Area2= " + area2); } }}

Constructors:A constructor is a special method of a class that is called indirectly when creating an object using the new keyword. Constructors have the same name as the class itself. Secondly, they do not specify a return type not even void. This is because they do not return any value. Consider the above example and observe how we are going to replace Getdata method with the constructor.namespace ClassExample1{ class rectangle { public int length, width; public rectangle(int x,int y) { length = x; width = y; } public int Rectarea() { int area = length * width; return area; } } class Program { static void Main(string[] args) { int area1, area2; rectangle rect1 = new rectangle(15,10); rectangle rect2 = new rectangle(20,12); area1=rect1.Rectarea(); area2 = rect2.Rectarea(); Console.WriteLine("Area1= " + area1); Console.WriteLine("Area2= " + area2); } }}

The Role of the Default ConstructorEvery C# class is provided with a freebee default constructor that you may redefine if need be. By definition, a default constructor never takes arguments. Beyond allocating the new object into memory, the default constructor ensures that all field data is set to an appropriate default value. Keep in mind that what makes one constructor different from another (in the eyes of the C# compiler) is the number of and type of constructor arguments. When you define a method of the same name that differs by the number or type of arguments, you have overloaded the method. Overloaded Constructors:As discussed earlier, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. We can extend the concept of method overloading to provide more than one constructor to a class.To create an overloaded constructor method, all we have to do is to provide several different constructor definitions with different parameter lists. The difference may be either the number or type of arguments. That is each parameter should be unique. namespace ClassExample1{ class rectangle { public int length, width; public rectangle(int x,int y) { length = x; width = y; } public rectangle(int x) { length = width = x; } public int Rectarea() { int area = length * width; return area; } } class Program { static void Main(string[] args) { int area1, area2; rectangle rect1 = new rectangle(15,10); rectangle rect2 = new rectangle(20); area1=rect1.Rectarea(); area2 = rect2.Rectarea(); Console.WriteLine("Area1= " + area1); Console.WriteLine("Area2= " + area2); } }}

The Role of this Keyword:Like other C-based languages, C# supplies a this keyword that provides access to the current class instance. One possible use of the this keyword is to resolve scope ambiguity, which can arise when an incoming parameter is named identically to a data field of the type. namespace ConstructorthisExample1{ class Example { int x; int y; public void SetXY(int x, int y) { this.x = x; this.y = y; } } class Program { static void Main(string[] args) { Example ExObj = new Example(); ExObj.SetXY(10, 20); } }}

Static KeywordWe have seen that a simple class contains two sections. One declares variables and the other declares methods. These variables and methods are called as instance variables and instance methods. This is because every time class is instantiated, a new copy of each is created. They are accessed using the objects (with dot operator).Let us assume that we want to define a member that is common to all the objects and accessed without using a particular object. That is, the member belongs to the class as a whole rather than the objects created from the class. A C# class (or structure) may define any number of static members via the static keyword. When you do so, the member in question must be invoked directly from the class level, rather than from a type instance. To illustrate the distinction, consider System.Console. As you have seen, you do not invoke the WriteLine() method from the object level:// Error! WriteLine() is not an instance level method!Console c = new Console();c.WriteLine("I can't be printed...");

but instead simply prefix the type name to the static WriteLine() member:

// Correct! WriteLine() is a static method.Console.WriteLine("Thanks...");

Simply put, static members are items that are deemed (by the type designer) to be so commonplace that there is no need to create an instance of the type when invoking the member.The members that are declared static are called static members. Since the members are associated with the class rather than with individual objects, the static variables and static methods are often referred to as class variables and class methods in order to distinguish from their counter parts.

Defining Static Methods (and Fields)namespace StaticmethodExample1{ class StaticDemo { // a static variable public static int val = 100;

// a static method public static int valDiv2() { return val / 2; } } class Program { static void Main(string[] args) { Console.WriteLine("Initial value of StaticDemo.val is " + StaticDemo.val);

StaticDemo.val = 8; Console.WriteLine("StaticDemo.val is " + StaticDemo.val); Console.WriteLine("StaticDemo.valDiv2(): " + StaticDemo.valDiv2()); } }}

Static members can operate only on static data and call static methods of the defining class. If you attempt to make use of nonstatic class data or call a nonstatic method of the class within a static members implementation, youll receive compile-time errors.

Static data is allocated once and shared among all instances of the class.

Static Constructors Static constructor is a special constructor that is an ideal place to initialize the values of static data when the value is not known at compile time (e.g., you need to read in the value from an external file, generate a random number, etc.). Here are a few points of interest regarding static constructors: A given class (or structure) may define only a single static constructor. A static constructor does not take an access modifier and cannot take any parameters. A static constructor executes exactly one time, regardless of how many objects of the type are created. The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller. The static constructor executes before any instance-level constructors. Given this modification, when you create new SavingsAccount objects, the value of the static data is preserved, as the static member is set only one time within the static constructor, regardless of the number of objects created.class SavingsAccount { public double currBalance; // A static point of data. public static double currInterestRate; public SavingsAccount(double balance) { currBalance = balance; } static SavingsAccount() { Console.WriteLine("In static ctor!"); currInterestRate = 0.04; } public static void SetInterestRate(double newRate) { currInterestRate = newRate; }}

Defining Static ClassesSince the release of .NET 2.0, the C# language expanded the scope of the static keyword by introducing static classes. When a class has been defined as static, it is not creatable using the new keyword, and it can contain only members or fields marked with the static keyword (if this is not the case, you receive compiler errors).Consider the following new static class type:static class TimeUtilClass { public static int a = 10; public static void PrintTime() { Console.WriteLine(DateTime.Now.ToShortTimeString()); } public static void PrintDate() { Console.WriteLine(DateTime.Today.ToShortDateString()); } }

Given that this class has been defined with the static keyword, we cannot create an instance of TimeUtilClass using the new keyword:static void Main(string[] args) { Console.WriteLine("***** Fun with Static Data *****\n"); TimeUtilClass.PrintDate(); // Compiler error! Can't create static classes. TimeUtilClass u = new TimeUtilClass(); }

C# Access ModifiersWhen working with encapsulation, you must always take into account which aspects of a type are visible to various parts of your application. Specifically, types (classes, interfaces, structures, enumerations, delegates) and their members (properties, methods, constructors, fields, and so forth) are always defined using a specific keyword to control how visible the item is to other parts of your application. Although C# defines numerous keywords to control access, they differ on where they can be successfully applied (type or member).Public items have no access restrictions. A public member can be accessed from an object as well as any derived class. A public type can be accessed from other external assemblies.

Private items can only be accessed by the class (or structure) that defines the item.

Protected items are not directly accessible from an object variable; however, they are accessible by the defining type as well as by derived classes.

Internal items are accessible only within the current assembly. Therefore, if you define a set of internal types within a .NET class library, other assemblies are not able to make use of them.

When the protected and internal keywords are combined on an item, the item is accessible within the defining assembly, the defining class, and by derived classes.

The Default Access ModifiersBy default, type members are implicitly private while types are implicitly internal. Thus, the following class definition is automatically set to internal, while the types default constructor is automatically set to private:// An internal class with a private default constructor.class Radio{Radio(){}}

Thus, to allow other types to invoke members of an object, you must mark them as publicly accessible. As well, if you wish to expose the Radio to external assemblies you will need to add the public modifier.// A public class with a public default constructor.public class Radio{Public Radio (){}}

Encapsulation: How does this language hide an objects internal implementation details and preserve data integrity?The first pillar of OOP is called encapsulation. This trait boils down to the languages ability to hide unnecessary implementation details from the object user. For example, assume you are using a class named DatabaseReader, which has two primary methods: Open() and Close():// This type encapsulates the details of opening and closing a database.DatabaseReader dbReader = new DatabaseReader();dbReader.Open(@"C:\MyCars.mdf");// Do something with data file and close the file.dbReader.Close();

The fictitious DatabaseReader class encapsulates the inner details of locating, loading, manipulating, and closing the data file. Object users love encapsulation, as this pillar of OOP keeps programming tasks simpler. There is no need to worry about the numerous lines of code that are working behind the scenes to carry out the work of the DatabaseReader class. All you do is create an instance and send the appropriate messages.The concept of encapsulation revolves around the notion that an objects internal data should not be directly accessible from an object instance. .NET languages prefer to enforce data protection using properties. Here is the Employee class, now enforcing encapsulation of each field using property syntax.class Employee{// Field data.private string empName;private int empID;private float currPay;// Properties.public string Name{get { return empName; }set { empName = value; }}public int ID{get { return empID; }set { empID = value; }}public float Pay{get { return currPay; }set { currPay = value; }}...}

A C# property is composed by defining a get scope (accessor) and set scope (mutator) directly within the property scope itself. Once we have these properties in place, it appears to the caller that it is getting and setting a public point of data; however, the correct get and set block is called behind the scenes to preserve encapsulation. One of the design goals of object-oriented systems is not to permit any direct access to data members, because of the implications of integrity.

namespace PropertiesExample1{ class Number { private int number; public int ANumber { get { return number; } set { number = value; } } } class Program { static void Main(string[] args) { Number N = new Number(); N.ANumber = 100; int m = N.ANumber; Console.WriteLine(m); } }}

When encapsulating data, you may wish to configure a read-only property. To do so, simply omit the set block. Likewise, if you wish to have a write-only property, omit the get block.Static PropertiesC# also supports static properties. namespace PropertiesExample1{ class MyClass { static int myValue;

public static int StaticProperty { set { myValue = value; } get { return myValue; } }

}

class MainClass { static void Main() { Console.WriteLine("Init Value: {0}", MyClass.StaticProperty); MyClass.StaticProperty = 10; Console.WriteLine("New Value : {0}", MyClass.StaticProperty); } }}

Read-Only Fields:There are situations where we want to decide the value of a constant member at run time. We may also like to have different constant values for different objects of the class. Closely related to constant data is the notion of read-only field data (which should not be confused with a read-only property). Like a constant, a read-only field cannot be changed after the initial assignment. However, unlike a constant, the value assigned to a read-only field can be determined at runtime, and therefore can legally be assigned within the scope of a constructor.namespace readonlyExample1{ public class MyClass { public MyClass() { SetField(ref this.y); }

private void SetField(ref int val) { val = 8; }

public readonly int x = 123; public readonly int y; public const int z = 555;

}

public class MainClass { static void Main() { MyClass obj = new MyClass();

System.Console.WriteLine("x = {0}, y = {1}, z = {2}",obj.x, obj.y, MyClass.z); }

}}

Methods &Parameter ModifiersIn Object-Oriented programming, objects are used as building blocks in developing a program. They are the runtime entities. Objects encapsulate data, and code to manipulate that data. The code designed to work on the data is known as methods in C#. C# is a pure object-oriented language and therefore, every method must be contained within a class. In other languages, we can define global functions that are not associated with a particular class.Declaring Methods:Methods are declared inside the body of a class, normally after the declaration of data fields. The general form of a method declaration is Modifiers type methodname (formal parameter list){ Method body}

Method declaration has five parts: Name of the method Type of the value that the method returns List of parameters Body of the method Method modifiersInvoking Methods: Once methods have been defined, they must be activated for operations. The process of activating a method is known as invoking or calling. The invoking is done using the dot operator as shown below: Objectname.methodname ( actual parameterslist)

Here the object name is the name of the object on which we are calling the method methodname. The actual parameter list is a comma separated list of actual values that must match in type, order and number with the formal parameter list of the methodname declared in the class. The invoking statement is an executable one and therefore must end with a semicolon. The values of the actual parameters are assigned to the formal parameters at the time of invocation. namespace InvokeMethodExample1{ class Method { public int cube(int x) { return x * x * x; } } class Program { static void Main(string[] args) { Method M = new Method(); int y = M.cube(5); Console.WriteLine(y); } }}

Method Parameters:A method invocation creates a copy, specific to that invocation, of the formal parameters and local variables of that method. The actual parameter list of the invocation assigns values or variables references to the newly created formal parameters. Within the body of a method, formal parameters can be used like any other variables.The invocation not only involves passing the values but also involves returning the values from the methods to the calling methods. For managing the process of passing values and getting back the results, C# employs four kinds of parameters1. Value parameter2. out parameters3. Reference parameters4. Parameters arraysPass By Value:By default, method parameters are passed by value. That is, a parameter declared with no modifier is passed by value and is called a value parameter. When a method is invoked, the values of actual parameters are assigned to the corresponding formal parameters. The values of the value parameters can be changed within the method. The value of the actual parameters that is passed by value to a method is not changed by any changes made to the corresponding formal parameters within the body of the method. This is because the methods refer only copies of those variables when they are passed by value.namespace PassByValueExample1{ class Program { static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes // as you are modifying a copy of the // original data. x = 10000; y = 88888; return ans; } static void Main(string[] args) { Console.WriteLine("***** Fun with Methods *****"); // Pass two variables in by value. int x = 9, y = 10; Console.WriteLine("Before call: X: {0}, Y: {1}", x, y); Console.WriteLine("Answer is: {0}", Add(x, y)); Console.WriteLine("After call: X: {0}, Y: {1}", x, y); Console.ReadLine(); } }}

The out Modifier:Next, we have the use of output parameters. Output parameters must be assigned by the method being called (and therefore are passed by reference). If the called method fails to assign output parameters, you are issued a compiler error. Methods that have been defined to take output parameters (via the out keyword) are under obligation to assign them to an appropriate value before exiting the method in question (if you fail to do so, you will receive compiler errors).To illustrate, here is an alternative version of the Add() method that returns the sum of two integers using the C# out modifier (note the physical return value of this method is now void): class Program { static void add1(int x, int y, out int add,out int sub) { add = x + y; sub = x - y; } static void Main(string[] args) { int a = 100; int b = 200; int add,sub; add1(a, b,out add,out sub); Console.WriteLine(add); Console.WriteLine(sub); } }

Finally, remember that methods that define output parameters must assign the parameter to a valid value before exiting the methods.The ref ModifierNow consider the use of the C# ref parameter modifier. Reference parameters are necessary when you wish to allow a method to operate on (and usually change the values of) various data points declared in the callers scope (such as a sorting or swapping routine). namespace RefExample1{ class Program { public static void SwapStrings(ref string s1, ref string s2) { string tempStr = s1; s1 = s2; s2 = tempStr; } static void Main(string[] args) { Console.WriteLine("***** Fun with Methods *****"); string s1 = "Flip"; string s2 = "Flop"; Console.WriteLine("Before: {0}, {1} ", s1, s2); SwapStrings(ref s1, ref s2); Console.WriteLine("After: {0}, {1} ", s1, s2); Console.ReadLine(); } }}

The params ModifierLast but not least, C# supports the use of parameter arrays. The params keyword allows you to pass into a method a variable number of parameters (of the same type) as a single logical parameter. As well, arguments marked with the params keyword can be processed if the caller sends in a strongly typed array or a comma-delimited list of items. namespace ParamsExample1{ class Program { static double CalculateAverage(params double[] values) { Console.WriteLine("You sent me {0} doubles.", values.Length); double sum = 0; if (values.Length == 0) return sum; for (int i = 0; i < values.Length; i++) sum += values[i]; return (sum / values.Length); } static void Main(string[] args) { Console.WriteLine("***** Fun with Methods *****"); // Pass in a comma-delimited list of doubles... double average; average = CalculateAverage(4.0, 3.2, 5.7, 64.22, 87.2); Console.WriteLine("Average of data is: {0}", average); // ...or pass an array of doubles. double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); // Average of 0 is 0! Console.WriteLine("Average of data is: {0}", CalculateAverage()); Console.ReadLine(); } }}

Method Over Loading:Like other modern object-oriented languages, C# allows a method to be overloaded. Simply put, when you define a set of identically named members that differ by the number (or type) of parameters, the member in question is said to be overloaded. Method overloading is used when methods are required to perform similar tasks but using different input parameters.Overloaded methods must differ in number of parameters they take. This enables the compiler to decide which one of the definitions to execute depending on type and number of arguments in the method call. The method return type does not play any role in the overload resolution.

namespace MethodOverLoadingExample1{ class Program { static int volume(int x) //cube { return x * x * x; } static double volume(float r, int h) //Cylinder { return (3.14519 * r * r * h); } static long volume(long l, int b, int h) //box { return (l * b * h); } static void Main(string[] args) { Console.WriteLine(volume(10)); Console.WriteLine(volume(2.5f, 8)); Console.WriteLine(volume(100L, 75, 15)); } }}

Inheritance:Will learn how to build families of related classes using inheritance. As you will see, this form of code reuse allows you to define common functionality in a parent class that can be leveraged (and possibly altered) by child classes. C# being a powerful Object oriented language supports the reuse feature. In fact the ability to create a new class from the existing classes is the major motivation and power behind using OOP languages. C# classes can be reused in several ways. Reusability is achieved by designing new classes, reusing all or some of the properties of the existing ones. The mechanism of designing or constructing one class from another is called inheritance.Classical Inheritance:Inheritance represents a kind of relationship between two classes. Let us consider two classes A and B. we can create a classy hierarchy such that B is derived from A. Class A, the initial class that used as the basis for the derived class is referred as base class, parent class or super class. Class B is referred as derived class, child class or sub class. A derived class is a completely new class that incorporates all the data and methods of its base class. It can also have its own data and method members that are unique to itself. That is, it can enhance the content and behavior of the base class. The classical inheritance may be implemented in different combinations. They include: Single Inheritance Multiple Inheritance Multilevel Inheritance

It does not directly implement multiple inheritance. However this concept is implemented using Interfaces.namespace Inheritanceexample1{ class Student { protected string name; protected int Stdid; protected void PrintStdDetails() { Console.WriteLine("Student Name:{0}\n Student Id:{1}", name, Stdid); } } class EEStudent : Student { string sub1; string sub2; public EEStudent(string s1, string s2) { sub1 = s1; sub2 = s2; name = "VMGSoft"; Stdid = 0863; } public void PrintDetails() { PrintStdDetails(); Console.WriteLine("Subject name1 :{0}\n subject2 name :{1}", sub1, sub2); } } class Program { static void Main(string[] args) { EEStudent EObj = new EEStudent("PoWerSystems", "Mahcines"); EObj.PrintDetails(); } }}

namespace Inheritanceexample2{ class Baseclass { int a; protected Baseclass() { Console.WriteLine("Base Class Constructor"); } public Baseclass(int x) { a = x; Console.WriteLine("Base Class Constructor with parameters"); } } class DerivedClass : Baseclass { int b; public DerivedClass():base() { Console.WriteLine("Derived Class Constructor with no parameters"); } public DerivedClass(int y,int y1) : base(y1) { b = y; Console.WriteLine("Derived Class Constructor with parameters"); } } class Program { static void Main(string[] args) { DerivedClass obj = new DerivedClass();

} }}

MultiLevel Inheritance:A common requirement in object oriented programming is the use of a derived class as a super class. C# supports this concept and uses it extensively in building its class library. This concept allows us to build a chain of classes.Class A{ . . . . . . . . . . . . . . .}Class B : A{ . . . . . . . . . . . . . . .}Class C:B{ . . . . . . . . . . . . . . .}

This process may be extended to any number of levels. The class C can inherit the members of both A and B.Nesting Classes:A nested class is one that is created inside another class. There are several reasons to have inner classes. Organizing code into real world situations where there is a special relationship between two objects.

Any object that can exist and be used independently of the relationship uses aggregation. Any object that has no meaning outside of the relationship uses composition. In the diagram above, the battery and the engine have no meaning outside of the car, as the car cannot work without either of them, so the relationship is formed using composition. However, a car can work without doors, so the relationship is formed using aggregation.A class named Car would have an engine. In UML, an object relationship that is formed by aggregation is drawn using an empty diamond. An object relationship that is formed using composition is drawn using a filled diamond. namespace NestingClassesExample1{ class MyClass { class MyCounter { public int Count = 0; }

MyCounter counter;

public MyClass() { counter = new MyCounter(); } public int Incr() { return counter.Count++; } public int GetValue() { return counter.Count; } }

class MainClass { static void Main() { MyClass mc = new MyClass();

mc.Incr(); mc.Incr(); mc.Incr(); mc.Incr(); mc.Incr(); mc.Incr();

Console.WriteLine("Total: {0}", mc.GetValue()); } }}

Polymorphism:This is the final pillar of the OOP. It is the ability to take more than one form. Polymorphism refers to being able to use many forms of a type without regard to the details. A classs polymorphism can be constructed using any number of virtual or abstract members. In a nutshell, a virtual member is a member in a base class that defines a default implementation that may be changed (or more formally speaking, overridden) by a derived class. In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type. In either case, when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.Polymorphism provides a way for a subclass to define its own version of a method defined by its base class, using the process termed method overriding. To retrofit your current design, you need to understand the meaning of the virtual and override keywords. If a base class wishes to define a method that may be (but does not have to be) overridden by a subclass, it must mark the method with the virtual keyword. When a subclass wishes to change the implementation details of a virtual method, it does so using the override keyword. namespace Polymorphism_Example1{ class baseclass { public virtual void display() { Console.WriteLine("Base class function is executed"); } } class Derivedclass : baseclass { public override void display() { Console.WriteLine("derived class function is executing"); } } class Program { static void Main(string[] args) { Derivedclass objder = new Derivedclass(); objder.display(); baseclass objbase = new Derivedclass(); objbase.display(); baseclass objbase2 = new baseclass(); objbase2.display(); Console.ReadLine(); } } }

Sealed Classes:Sometimes, we may like to prevent a class being further subclassed for security reasons. A class that cannot be subclassed is called a sealed class. This is achieved in C# using the modifier sealed. C# supplies another keyword, sealed, that prevents inheritance from occurring. When you mark a class as sealed, the compiler will not allow you to derive from this type. Sealed Methods:class A { public virtual void F() { Console.WriteLine("A.F"); } public virtual void G() { Console.WriteLine("A.G"); } } class B : A { sealed override public void F() { Console.WriteLine("B.F"); } override public void G() { Console.WriteLine("B.G"); } } class C : B { override public void G() { Console.WriteLine("C.G"); } override public void F() { Console.WriteLine("B.F"); } } class Program { static void Main() { } }

Partial Classes:It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. There are several situations when splitting a class definition is desirable: When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.namespace PolyExample1{ internal partial class XY { int x;

public int X { get { return x; } set { x = value; } } } partial class XY { int y;

public int Y { get { return y; } set { y = value; } } public void Display() { Console.WriteLine(x + " " + y); } } class MainClass { public static void Main() { XY xy = new XY(); Console.WriteLine(xy.X + "," + xy.Y); } }}

Abstract classes:The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. Classes can be declared as abstract by putting the keyword abstract before the class definition. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class. abstract class absClass{ public abstract void abstractMethod();}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class. An abstract class cannot be a sealed class.Declaration of abstract methods is only allowed in abstract classes.An abstract method cannot be private.The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.namespace AbstractExample1{ abstract class absClass { //A Non abstract method

public int AddTwoNumbers(int Num1, int Num2) { return Num1 + Num2; } public abstract int MultiplyTwoNumbers(int Num1, int Num2); }

class absDerived:absClass { public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1 * Num2; } }

class Program { static void Main(string[] args) { absDerived calculate = new absDerived(); int added = calculate.AddTwoNumbers(10,20); int multiplied = calculate.MultiplyTwoNumbers(10, 20); Console.WriteLine("Added : {0},Multiplied : {1}", added, multiplied);

} }}

An abstract method cannot be static, since abstract methods MUST be overridden by concrete implementations, and static methods cannot be overridden by definition. If a subclass re-declares a static method, it hides the base class method, it doesn't override it. Overriding only makes sense in terms of instance variables (think VMT) - static method implementations are determined by the compiler - hence hidden, not overridden.InterfacesWhen trying to build maintainable, reusable, and flexible C# code, the object oriented nature of C# only gets us 50% of the way there. Programming to interfaces can provide us with the last 50%. Interfaced-based design provides easier maintainability and it makes code reuse much more accessible because implementation is separated from the interface.Previously we discussed the various features of classes and how they can be inherited by other classes. We also learned about various forms of Inheritance and pointed out that C# doesnt support multiple Inheritance. A large number of real-life applications require the use of multiple inheritance whereby we inherit the methods and properties from different classes. Since C++ like implementation of multiple inheritance proves difficult and adds complexity to the language, C# provides an alternative approach known as interface to support the concept of multiple inheritance. Although C# cannot subclass more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritance. An Interface in C# is a reference type. It is basically a kind of class with some differences. Major differences include: All the members of an interface are implicitly Public and Abstract. An interface cannot contain constant fields, constructors and destructors Its members cannot be declared as static Since the methods in an interface are abstract, they do not include implementation code An interface can inherit multiple interfaces.Simply An interface is nothing more than a named set of abstract members. An interface expresses a behavior that a given class or structure may choose to implement. Interfaces are used to encode similarities which classes of various types share, but do not necessarily constitute a class relationship.

Defining an Interface:An interface can contain one or more methods, properties, indexers, and events but none of them are implemented in the interface itself. It is the responsibility of the class that implements the interface to define the code for implementation of these members.The syntax for defining an interface is very similar to that used for defining a class. The general form of the interface definition is:Interface InterfaceName{ Member declarations;}

Here, Interface is the keyword and InterfaceName is the valid C# identifier. Member declarations will contain only members without implementation code. Given below is a simple interface that defines a single method:Interface IShow{ Void display ();}

By convention, .NET interface types are prefixed with a capital letter I. When you are creating your own custom interfaces, it is considered a best practice to do the same.In addition to methods an Interface may also contain properties, indexers and events.

Interface types are quite useless on their own, as they are nothing more than a named collection of abstract members. For example, you cannot allocate interface types as you would a class or structure:

// Illegal to allocate interface types.Static void Main (string[] args){Iinterface p = new Iinterface (); // Compiler error!}

Extending an Interface:Like classes, interfaces can also be extended. That is an interface can be sub interfaced from other interfaces. The new sub interface will inherit all the members of the super-interface in the manner similar to sub-classes. This is achieved as follows:Interface name2 : name1{ Members of name2;}

For example, we can put all members of particular behavior category in one interface and the members of another category in the order.Consider the code below:Interface Addition{ Int Add (int x, int y);}Interface Computation : Addition{ Int sub (int x, int y);}

The interface compute will have both the methods and any class implementing the interface Compute should implement both of them; otherwise it is an error. We can also combine several interfaces together into a single interface.Implementing Interfaces:Interfaces are used as super-classes whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. When a class (or structure) chooses to extend its functionality by supporting interface types, it does so using a comma-delimited list in the type definition. Be aware that the direct base class must be the first item listed after the colon operator.This is done as follows:Class classname : interfacename{ Body of classname;}

interface addition { int add(); } interface multiplication { int mul(); } class computation : addition, multiplication { int x, y; public computation(int x, int y) { this.x = x; this.y = y; } public int add() { return (x + y); } public int mul() { return x * y; } } class Program { static void Main(string[] args) { int z,t; computation objcomp = new computation(10, 5); z = objcomp.add(); Console.WriteLine(z); t = objcomp.mul(); Console.WriteLine(t); } }

interface Area { double Compute(double x);

} class Square : Area { public double Compute(double x) { return x * x; } } class Circle : Area { public double Compute(double x) { return (Math.PI * x * x); } } class Program { static void Main(string[] args) { //invoking the members at object level Square sqr = new Square(); Circle cir = new Circle(); Console.WriteLine("The area of Square is {0}", sqr.Compute(10)); Console.WriteLine("The area of circle is {0}", cir.Compute(20.0));

//obtaining interface references Area area = sqr as Area; Console.WriteLine("The area of Square is {0}", area.Compute(10.0)); area = cir as Area; Console.WriteLine("The area of circle is {0}", area.Compute(10.0)); Console.ReadLine();//obtaining interface references abc = (Area) cir; } }

interface I1 { void display(); } interface I2 { void display(); } class C1 : I1, I2 { void I1.display() { Console.WriteLine("I1 Display"); } void I2.display() { Console.WriteLine("I2 display"); } } class Program { static void Main(string[] args) { C1 c = new C1(); I1 i1 = (I1)c; i1.display(); I2 i2 = (I2)c; i2.display(); Console.ReadLine(); } }

Points to Remember

In .NET platform, the most fundamental programming construct is the class type. Class is a user-defined type that is composed of field data (often called member variables) and members that operate on this data. A class with only data fields and without methods that operate on data has no life. C# provides a set of access modifiers that can be used with members of a class to control their visibility to the outside users. The new operator creates an object of the specified class and returns a reference to that object. A constructor is a special method of a class that is called indirectly when creating an object using the new keyword. Every C# class is provided with a freebee default constructor. Static constructor is a special constructor that is an ideal place to initialize the values of static data when the value is not known at compile time. The static constructor executes before any instance-level constructors. Encapsulation is the languages ability to hide unnecessary implementation details from the object user. .NET languages prefer to enforce data protection using properties. The mechanism of designing or constructing one class from another is called inheritance. C# does not support multiple inheritance for class types. Polymorphism refers to being able to use many forms of a type without regard to the details. When you mark a class as sealed, the compiler will not allow you to derive from this type. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. Declaration of abstract methods is only allowed in abstract classes. An interface can contain one or more methods, properties, indexers, and events but none of them are implemented in the interface itself.

Check YourSelf

Exercise: Explain about the differences between Abstract classes and Interfaces. Write a Program to implement polymorphism in Multi-Level Inheritance Write a Program using Interfaces to implement multiple Inheritance where two interfaces are having the same Method. Explain about this keyword and write a Program to implement constructor chaining. Explain about the differences between ref, out and Params modifiers. Write a Program by implementing Properties in the Abstract Classes and overriding them in the derived classes.