Object Oriented

Published on June 2017 | Categories: Documents | Downloads: 31 | Comments: 0 | Views: 512
of 31
Download PDF   Embed   Report

Comments

Content

NEED FOR ENCAPSULATION: The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions. Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways. Let us see some example programs in C# to demonstrate Encapsulation by those two methods. The first method is using a pair of conventional accessor and mutator methods. Another one method is using a named property. Whatever be the method our aim is to use the data with out any damage or change. ENCAPSULATION USING ACCESSORS AND MUTATORS: Let us see an example of Department class. To manipulate the data in that class (String departname) we define an accessor (get method) and mutator (set method). using system; publicclass Department { privatestringdepartname; ....... // Accessor. publicstringGetDepartname() { returndepartname; } // Mutator. publicvoidSetDepartname( string a) { departname=a; } }

Like the above way we can protect the private data from the outside world. Here we use two separate methods to assign and get the required data. publicstaticint Main(string[] args) { Department d = new Department(); d.SetDepartname("ELECTRONICS"); Console.WriteLine("The Department is :"+d.GetDepartname()); return 0; }

In the above example we can't access the private data departname from an object instance. We manipulate the data only using those two methods. ENCAPSULATION USING PROPERTIES: Properties are a new language feature introduced with C#. Only a few languages support this property. Properties in C# helps in protect a field in a class by reading and writing to it. The first method itself is good but Encapsulation can be accomplished much smoother with properties. Now let's see an example. using system; publicclass Department { privatestringdepartname; publicstringDepartname { get { returndepartname; } set { departname=value; } } } publicclassDepartmentmain { publicstaticint Main(string[] args) { Department d= new Department(); d.departname="Communication"; Console.WriteLine("The Department is :{0}",d.Departname); return 0; } } From the above example we see the usage of Encapsulation by using properties. The property has two accessor get and set. The get accessor returns the value of the some property field. The set accessor sets the value of the some property field with the contents of "value". Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation. READ ONLY PROPERTY: using system; publicclassReadDepartment { privatestringdepartname; publicReadDepartment(stringavalue)

{ departname=avalue; } publicstringDepartname { get { returndepartname; } } } publicclassReadDepartmain { publicstaticint Main(string[] args) { ReadDepartment d= newReadDepartment("COMPUTERSCIENCE"); Console.WriteLine("The Department is: {0}",d.Departname); return 0; } } In the above example we see how to implement a read-only property. The class ReadDepartment has a Departname property that only implements a get accessor. It leaves out the set accessor. This particular class has a constructor, which accepts a string parameter. The Main method of the ReadDepartmain class creates a new object named d. The instantiation of the d object uses the constructor of the ReadDepartment that takes a string parameter. Since the above program is read-only, we cannot set the value to the field departname and we only read or get the value of the data from the field. Properties can be made also Write-only. This is accomplished by having only a set accessor in the property implementation. WRITE ONLY PROPERTY: using system; publicclassWriteDepartment { privatestringdepartname; publicstringDepartname { set { departname=value; Console.WriteLine("The Department is :{0}",departname); } } } publicclassWriteDepartmain { publicstaticint Main(string[] args) { WriteDepartment d= newWriteDepartment(); d.departname="COMPUTERSCIENCE";

return 0; } } In the above example we see how to implement a Write-only property. The class WriteDepartment has now has a Departname property that only implements a set accessor. It leaves out the get accessor. The set accessor method is varied a little by it prints the value of the departname after it is assigned. CONCLUSION: The Encapsulation is the first footstep towards the object-oriented programming. This article gives you a little bit information about Encapsulation. Using accessor and mutator methods we can make encapsulation. Another one method is using a named property. The benefit of properties is that the users of your objects are able to manipulate the internal data point using a single named item.

What is Encapsulation?
y y y y y y y y y y y

Encapsulation is one of the fundamental principles of object-oriented programming. Encapsulation is a process of hiding all the internal details of an object from the outside world Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required Encapsulation is a protective barrier that prevents the code and data being randomly accessed by other code or by outside the class Encapsulation gives us maintainability, flexibility and extensibility to our code. Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class. Encapsulation provides a way to protect data from accidental corruption Encapsulation hides information within an object Encapsulation is the technique or process of making the fields in a class private and providing access to the fields using public methods Encapsulation gives you the ability to validate the values before the object user change or obtain the value Encapsulation allows us to create a "black box" and protects an objects internal state from corruption by its clients.

Two ways to create a validation process.
y y

Using Accessors and Mutators Using properties

In this example _employeeid and _salary is private fields and providing access to the fields using public methods (SetEmployeeID,GetEmployeeID,SetSalary,GetSalary)

In this example _employeeid and _salary is private fields and providing access to the fields using public methods (EmployeeID,Salary)

Benefits of Encapsulation
y y y

In Encapsulation fields of a class can be read-only or can be write-only A class can have control over in its fields A class can change data type of its fields anytime but users of this class do not need to change any code

Introduction The constructor plays significant role in the nay kind of programming language. Here I explained the types of constructor and its limitation with suitable examples. Let us see the constructor. Constructors: The constructor is a special method to the class and struts. This constructor is used to initialize the types and objects. The complier consider as constructor when the constructor have the same name as class name. Every class has the default constructor in the class (default constructor). Which can be called as implicit constructor. This can be used to define the default values the data types when there are not defined. The user can use the default constructor for explicitly to create the instance of the classes. The constructor access modifier is public then it will be executed when the object is instantiated. The private constructor cannot be declaring. When object instantiate the outside class then it will throw an error like protection level. The internal also can be defined access modifier to the class constructor that will support up to that current assembly. Limitations: y y y y The constructor should have the same as the class or struct name. It cannot return any values to the calling program or function. It static constructor cannot have any parameters. It should have public or internal access modifiers. It can be declared as private but no use of it. When we instantiate the object it must throw compilation error like inaccessible due to protection level. It can be used to capture the parameters and initialize the values rather than do the complex logics.

y

Constructor: The simple constructor can be used to instantiate the object and define the data type values. The syntax of the constructor is the following access-modifier Class_Name(data type Parameter1,data type Parameter 2, [Classes Obj]) { //Code here } using System; publicclassSimpCons { privateint a; privateint b; publicSimpCons(int x, int y)

{ a = x; b = y; Display(); } publicvoid Display() { Console.WriteLine("The value of a is " + a); Console.WriteLine("The value of b is " + b); } } classSimpleConstructor { publicstaticvoid Main() { SimpConsoSimpCons = newSimpCons(5, 5); } } In the above code, the constructor is used to initialize the values to the variables. The constructor can be called the user defined the method in the both base and inherited class. Suppose I have not used the constructor then it will use the implicit constructor to initialize the values for the variables. Overload Constructor The constructor can be overloaded. As you know the constructor should be same as class name. But it can be overloaded just like method overloading. The same polymorphism concept can be applicable for the constructor. The same method name with different arguments. Overload Constructor with different data types The constructor can be overloaded with the same name of the constructor with different signature. The compiler only considers the signature type of the constructor. The arguments may be like int, string, char, float, double, etc.., using System; classOverCons { publicOverCons() { Console.WriteLine("Hi! Welcome to Overload Constructor"); Console.WriteLine("-----------------------------------"); } publicOverCons(int a, int b) { Console.WriteLine("The addition of " + a + " and " + b + " is " + (a + b)); } publicOverCons(string str1, string str2) { Console.WriteLine("Your full name is " + (str1 + str2));

} } classConstuctorOverload { publicstaticvoid Main(string[] args) { OverConsoOverCons = newOverCons(); OverCons oOverCons1 = newOverCons(90, 10); OverCons oOverCons2 = newOverCons("Senthil", "kumar"); } } This example shows there are three overloaded constructors. One is default constructor, second one is it accepts two integer values. Final constructor accepts the string. It can be any different combination of data types of parameter to the functions. It will not allow the constructor with the same signature types with different variable name. Because the compiler identifies the constructor based on the type of signature matches. Overload Constructor with different class objects When overload the constructors it accepts the different types of class objects. It can be overloaded with the objects. using System; usingSystem.Collections; usingSystem.Text; classObjOver { publicObjOver(ArrayListoArrayList) { Console.WriteLine("Constructor - ArrayList"); Console.WriteLine("-----------------------"); for (int i = 0; i <oArrayList.Count; i++) { Console.WriteLine(oArrayList[i].ToString()); } } publicObjOver(StackoStack) { Console.WriteLine("Constructor - Stack"); Console.WriteLine("-------------------"); foreach (stringstrinoStack) { Console.WriteLine(str); } } publicObjOver(StringBuilderoSB) { Console.WriteLine("Constructor - StringBuilder"); Console.WriteLine("---------------------------"); Console.WriteLine(oSB.ToString());

} } classObjOverCons { publicstaticvoid Main(string[] args) { ArrayListoArrayList = newArrayList(); for (int i = 0; i < 10; i++) { oArrayList.Add(i); } StackoStack = newStack(); oStack.Push("Senthil"); oStack.Push("Kumar"); StringBuilderoSB = newStringBuilder(); oSB.Append("Welcome To Object Overload Constructor"); oSB.Append(Environment.NewLine); oSB.Append("Sample programs developed by Erode Senthilkumar"); ObjOver oObjOver1 = newObjOver(oArrayList); ObjOver oObjOver2 = newObjOver(oStack); ObjOver oObjOver3 = newObjOver(oSB); } } Here the constructor has overloaded with the class objects. Private Constructor The private constructor is a special method in the class. It can be only defined when the class has only the static members. using System; publicclassStaticBase { privateStaticBase() { Console.WriteLine("Hi"); } publicstaticvoid Display() { Console.WriteLine("Display() method"); } } classPrivateStatic { publicstaticvoid Main(string[] args) { StaticBase.Display(); } }

Here the below code cannot be executed. Here inherited class "DeriveCons" when try to access the properties of the "BaseCons" then the constructor method is defined as private access modifier. So it will throw exception like due to protection level. using System; publicclassBaseCons { privateBaseCons() { Console.WriteLine("BaseCons Constructor"); } } publicclassDeriveCons : BaseCons { publicDeriveCons() { Console.WriteLine("DeriveCons - Constructor"); } } classPrivateCons { publicstaticvoid Main(string[] args) { DeriveConsoDeriveCons = newDeriveCons(); } } Static Constructor: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers. using System; classBaseStatic { publicstaticint i; staticBaseStatic() { i = 100; Console.WriteLine("BaseStatic Constructor"); Console.WriteLine("i value is " + i); } } classStaticCons { publicstaticvoid Main(string[] args) { Console.WriteLine("Static Constructor"); Console.WriteLine("------------------"); BaseStaticoBaseStatic = newBaseStatic(); }

} In the above example, the static constructor will allow us to initialize the values for that static variable. It will not allow to use any other type variable. The below will throw an error. Because I have tried to initialize the non static variable. using System; classBaseClass { publicstaticint i; publicint a = 0; staticBaseClass() { i = 10; a = 15; } publicvoid Print() { Console.WriteLine("The value of i is " + i); Console.WriteLine("The value of a is " + a); } } classStaticCons1 { publicstaticvoid Main(string[] args) { BaseClassoBaseClass = newBaseClass(); oBaseClass.Print(); } } Behavior of the Constructor in the Inheritance As you know the constructor can call the method of the class. In the below mentioned code there are two classes. One is base class and another one is Derived class. The derived class inherited from the base class. In the main program we have instantiated the Derived class. The Base class has the virtual method name called Display. It has overridden in the Derived Class. If I instantiate the Derived class then which constructor will call first? using System; publicclassBaseClass { publicstring _ClassState; publicBaseClass() { _ClassState = "Base Class"; Console.WriteLine(_ClassState); Display(); } publicvirtualvoid Display() { Console.WriteLine("Base Class - Display()");

} } classDerivedClass : BaseClass { publicDerivedClass() { _ClassState = "Derived Class"; Console.WriteLine(_ClassState); } publicoverridevoid Display() { Console.WriteLine("Derived Class - Display()"); } } classInherVirtualCons { publicstaticvoid Main(string[] args) { DerivedClassoDerivedClass = newDerivedClass(); } } Yes! You are right!! The base class constructor will call first. Again I have called the method name in the Display. Actually I was expecting the base class Display method call first. But without call the Derived Class constructor it has called the Derived class Display method. In this scenario it considers only the current derived object method. Exception Handling in the Constructors The constructor will allow handling the exception. Before that we no need to write the more complex logics in the constructors. It has to be used to initialize the data types and create the object for the built in classes. using System; classConsExcep { publicConsExcep(intnumer, intdinom) { try { int Result = numer / dinom; Console.WriteLine("Result is:" + Result); } catch (ExceptionoEx) { Console.WriteLine("Error :" + oEx.Message); } } } classExcepConstructor { publicstaticvoid Main(string[] arsg) {

ConsExcepoConsExcep = newConsExcep(5, 0); } } Here it handles the divide by zero exception. Constructor in Partial Class As we know this partial class is the new feature from C# 2.0 onwards. The same class name can be divided into multiple classes with the same class name and different class file name along with partial keyword. Here a class can have the constructor in the different file name. As we know while compilation the compiler will build the same class name in the different file as single code unit. using System; publicpartialclassPartialClass { publicPartialClass() { Console.WriteLine("PartialClass Constructor"); } publicvoid Display() { Console.WriteLine("PartialClass - Display()"); } } publicpartialclassPartialClass { /* public PartialClass() { Console.WriteLine("PartialClass Constructor1"); } */ publicPartialClass(stringstrName) { Console.WriteLine("Name: " + strName); } publicvoid Print() { Console.WriteLine("PartialClass - Print()"); } } classPartialCons { publicstaticvoid Main(string[] args) { PartialClassoPartialClass = newPartialClass(); oPartialClass.Display(); oPartialClass.Print(); PartialClass oPartialClass1 = newPartialClass("Erode Senthilkumar");

} } Here the example shows the same default signature cannot have more than once in the every class. Because it will became ambiguity method while compiler compile these files into the single unit. But we can load the constructor in the different signatures in the every partial class. Constructors in Struct The struct can have the constructors. But it differs from the classes. The struct is value type. It will be stored on the stack. We have seen that class can have the default constructor explicitly. But here stack will not allow writing the default constructor. It should contain the parameter. But we can overload the constructor in the struct. Every struct has the default implicit constructor. It will get execute internally to initialize the default value to the variables. . But we cannot have the default constructor with out any parameter in the struct like the following. structEmployee { public Employee() { Console.WriteLine("Default Constructor in struct"); } } The struct should contain the constructor with the parameters like the following. using System; structstructstudent { privatestring _Sname; privatestring _Class; privatestring _Age; publicstructstudent(stringsname, stringsclass, string sage) { _Sname = sname; _Class = sclass; _Age = sage; } publicvoidPrintReport() { Console.WriteLine("Student Report"); Console.WriteLine("--------------"); Console.WriteLine("Student Name: " + _Sname); Console.WriteLine("Student Class: " + _Class); Console.WriteLine("Student Age: " + _Age); } } classStructCons { publicstaticvoid Main(string[] args) {

structstudentoSD = newstructstudent("Rama", "1st Std", "6"); oSD.PrintReport(); } } In the above struct is a valid one

What are constructors: A constructor is a special kind of method that has the same name as it's class and that gets executed when it's (class) object is created. In other words a constructor is a class default method that gets automatically executed whenever a class's object is created or whenever the class is initialized. Consider this example publicclassdemo { public demo () { //A default Constructor } kjkjhjkhjhjkh //Class members } In this example, the method demo() is called the constructor of the class demo; also called the default constructor. How it works: whenever you try to create an object of a class or initialize a class, then the default constructor will automatically be invoked. //Initializes the Class demo object = newdemo(); Point to remember about constructor 1. 2. 3. 4. A constructor can't be inherited, although a derived class can class the base class constructor. You have to explicitly write a default constructor (see below) while overloading constructors. Concept declaring multiple constructors of a class with different sets of parameters known as constructor overloading. A constructor can call another constructor of the same class using this().

Types of Constructor: 1. Default constructor: A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by

using the new operator and no arguments are provided to new. 2. Parameterized constructor: when we initialize class members during instantiation we can use a parameterized constructor which is similar to a default constructor except with parameters.

The following is a code example: publicclassdemo { public demo() { //A default Constructor } public demo(String Name) { //A parameterized Constructor having one parameter| } public demo(StringFirstName, StringLastName) { //A parameterized Constructor having two parameters } //Class members } When you create a parameterized constructor, we need to also declare a default constructor explicitly. Access modifier for constructor 1. 2. Public constructor: Constructors are public by default. Private constructor: It is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. publicclassdemo { private demo() { //A default Constructor as private } } So when we will try to create an object of this class, it will generate an error.

I.e. demo object = new demo () //Error Is there any way to create an object of this class. We can instantiate the class above by declaring another public constructor that has parameters. publicclassdemo { private demo() { //A default Constructor as private } public demo(StringstrName): this() { System.Console.WriteLine("Hello Mr. : " + strName); } //Class members } And now you can initialize an object of this class: demo object = new demo() , which will work fine.

3.

Static Constructor: A static constructor is used to initialize any static data, or to perform an action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced. publicclassdemo { static demo() { //A static Constructor // Can only access static members here. System.Console.WriteLine("I am a static constructor."); } } So when we create an object of this class, "I am a static constructor" gets printed. Examine the code below as well: publicclassdemo { static demo() { //A static Constructor // Can only access static members here.

System.Console.WriteLine("I am a static constructor."); } public demo() { //A default Constructor } //Class members } This example also prints the same result, "I am a static constructor". Point to remember about static constructor: 1. 2. 3. 4. A static constructor should not be declared with any access modifier. A static constructor does not accept parameters. A static constructor is called automatically. There is no way to call a static constructor directly.

How to call parent class constructor in derived class during inheritance Answer: It can be achieved by using base(). Example: classProgram { publicclassparent { public parent () { //A default Constructor } public parent (StringstrName) { //A parameterized Constructor having one parameter } //Class members } publicclasschild : parent { public child () { //A default Constructor }

public child (StringstrName) : base(strName) { //A parameterized Constructor having one parameter } //Class members staticvoid Main() { child object1 = newchild (); //1* child object2 = newchild ("Vishal Nayan"); //2* } } Inheritance is a relationship that defines one entity in terms of another. Class inheritance defines a new class in terms of one parent class or one or more interfaces. The new class inherits its interface and implementation from its parent class and method signatures. The new class is called a subclass or a derived class. Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations. Classes in C# support only single inheritance, and Object is the ultimate base class for all classes. The classes shown in earlier examples all implicitly derive from Object. Access modifiers in a classes members give different levels of access to derived classes. Below is a table that describes the access a child class has to the members of the inherited class depending upon the access modifier. access-specifier: public Parent class access modifier Access in child class public accessible protected accessible private not accessible

Table 5.6: Access-Specifier Members and inheritance scope C# only makes use of public inheritance, meaning that you cannot specify an inheritance modifier in C#. (Refer to the C# Language Specification, available at

http://msdn.microsoft.com/net/ecma/, for more details and recent updates to the C# language.) Listing 5.50 shows an example of a class deriving inheritance with public access specified. Listing 5.50: Inheritance Example 1 using System; classA// derived from object behind the scenes { publicvoid F() { Console.WriteLine("A.F"); } } classB : A// B inherits A { publicvoid G() { Console.WriteLine("B.G"); } } classTest { staticvoid Main() { Bb = newB(); b.F(); // Inherited from A b.G(); // Introduced in B Aa = b; // Treat a B as an A, polymorphic access a.F(); Console.ReadLine(); } } Listing 5.51: Inheritance Example 2 // example1 protected classA { protectedint x = 123; } classB : A { void F() { Aa = newA(); Bb = newB(); a.x = 10; // Error b.x = 10; // OK }

} Listing 5.52 shows another example of private inheritance that enables direct access to protected members. Listing 5.52: Protected.cs, Protected Modifier Example // example2 protected using System; classMyClass { protectedint x; protectedint y; } classMyDerivedC : MyClass//private inheritance { publicstaticvoid Main() { MyDerivedCmC = newMyDerivedC(); // Direct access to protected members: mC.x = 10; mC.y = 15; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); Console.ReadLine(); } } Figure 5.12 contains the resulting screen output.

Figure 5.12: Screen Output Generated from Listing 5.52 Conclusion Hope this article would have helped you in Inheritance in C#. See other articles on the website on .NET and C#.

Method Overloading

1. In C#, two or more methods within the same class can share the same name, as long as their parameter declarations are different. 2. These methods are said to be overloaded 3. The process is referred to as method overloading. 4. Method overloading is one of the ways to implement polymorphism. 5. It is not sufficient for two methods to differ only in their return types. 6. The methods must differ in the types or number of their parameters.
class Swapper { // this Swap() method swaps two int parameters public void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; }

// this Swap() method swaps two float parameters public void Swap(ref float x, ref float y) { float temp = x; x = y; y = temp; } } public class Example5_9 { public static void Main() { // create a Swapper object Swapper mySwapper = new Swapper(); // declare two int variables int intValue1 = 2; int intValue2 = 5; System.Console.WriteLine("initial intValue1 = " + intValue1 + ", intValue2 = " + intValue2); // swap the two float variables // (uses the Swap() method that accepts int parameters) mySwapper.Swap(ref intValue1, ref intValue2); // display the final values System.Console.WriteLine("final ", intValue2 = " + intValue2); intValue1 = " + intValue1 +

// declare two float variables float floatValue1 = 2f; float floatValue2 = 5f; System.Console.WriteLine("initial floatValue1 = " + floatValue1 + ", floatValue2 = " + floatValue2); // swap the two float variables // (uses the Swap() method that accepts float parameters) mySwapper.Swap(ref floatValue1, ref floatValue2); // display the final values System.Console.WriteLine("final floatValue1 = " + floatValue1 + ", floatValue2 = " + floatValue2); mySwapper.Swap(ref floatValue1, ref floatValue2); } } using System;

namespace MethodOverloading { public class Time1 { // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; // public accessor methods public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second); } // constructors public Time1(System.DateTime dt) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; } public Time1(int Year, int Month, int Date, int Hour, int Minute, int Second) { this.Year = Year; this.Month = Month; this.Date = Date; this.Hour = Hour; this.Minute = Minute; this.Second = Second; } } public class MethodOverloadingTester { public void Run() { System.DateTime currentTime = System.DateTime.Now; Time1 time1 = new Time1(currentTime); time1.DisplayCurrentTime(); Time1 time2 = new Time1(2000,11,18,11,03,30); time2.DisplayCurrentTime(); } static void Main() {

MethodOverloadingTester t = new MethodOverloadingTester(); t.Run(); } } }

using System; class Overload { public void ovlDemo() { Console.WriteLine("No parameters"); } // Overload ovlDemo for one integer parameter. public void ovlDemo(int a) { Console.WriteLine("One parameter: " + a); } // Overload ovlDemo for two integer parameters. public int ovlDemo(int a, int b) { Console.WriteLine("Two parameters: " + a + " " + b); return a + b; } // Overload ovlDemo for two double parameters. public double ovlDemo(double a, double b) { Console.WriteLine("Two double parameters: " + a + " "+ b); return a + b; } } class MainClass { public static void Main() { Overload ob = new Overload(); int resI; double resD; // call all versions of ovlDemo() ob.ovlDemo(); Console.WriteLine(); ob.ovlDemo(2); Console.WriteLine(); resI = ob.ovlDemo(4, 6); Console.WriteLine("Result of ob.ovlDemo(4, 6): " + resI); Console.WriteLine(); resD = ob.ovlDemo(1.1, 2.32); Console.WriteLine("Result of ob.ovlDemo(1.1, 2.32): " +

resD); }

namespace nsOverload { using System; public class clsMainOverload { static public void Main () { int iVal = 16; long lVal = 24; Console.WriteLine ("The square of {0} is {1}\r\n", iVal, Square(iVal)); Console.WriteLine ("The square of {0} is {1}", lVal, Square(lVal)); } static int Square (int var) { Console.WriteLine ("int Square (int var) method called"); return (var * var); } static long Square (long var) { Console.WriteLine ("long Square (long var) method called"); return (var * var); } } }

What is Method Overriding in C#? Method Overriding in C# is a type of Dynamic Polymorphism in which binding of method call to actual method implementation happens only during runtime. Method overriding in C# is achieved through inheritance. If a class is inherited by a derived class, then the derived class can override the base class method. This concept is termed as Method Overriding. How to implement Method Overriding in C#? Method Overriding is implemented in C# using the keywords virtual and override. The base class method that has to be overridden must be marked as virtual or abstract (if the base class is an abstract class). The derived class method that overrides the base class method should be marked with the keyword override. Most importantly, the method signature including argument list and return type should be same in the overridden method. The access modifier of the overridden method can have a wider scope but the scope cannot be narrowed. Method Overriding Example in C#:
using System;

//Method Overriding Example in C# classbaseClass { //The method methodOverridingExample is marked as virtual to permit method overriding public virtual void methodOverridingExample() { Console.WriteLine("Executing methodOverridingExample method of baseClass«"); } } class methodOverridingDerivedClass1 : baseClass { //The overridden method methodOverridingExample is marked with override keyword public override void methodOverridingExample() { Console.WriteLine("Executing methodOverridingExample method of methodOverridingDerivedClass1«"); } } class methodOverridingDerivedClass2 : baseClass { public override void methodOverridingExample() { Console.WriteLine("Executing methodOverridingExample method of methodOverridingDerivedClass1«"); }

} public class testMethodOverridingExample { public static void Main() { baseClass baseClassIns1 = new baseClass(); Console.WriteLine("Triggering: baseClass baseClassIns1 = new baseClass();"); baseClassIns1.methodOverridingExample(); baseClass baseClassIns2 = new methodOverridingDerivedClass1(); Console.WriteLine("Triggering: baseClass baseClassIns2 = new methodOverridingDerivedClass1();"); baseClassIns2.methodOverridingExample(); baseClass baseClassIns3 = new methodOverridingDerivedClass2(); Console.WriteLine("Triggering: baseClass baseClassIns3 = new methodOverridingDerivedClass2();"); baseClassIns3.methodOverridingExample(); Console.ReadLine(); } }

olymorphism

This lesson teaches about Polymorphism in C#. Our objectives are as follows:
y y y y

Learn What Polymorphism Is. Implement a Virtual Method. Override a Virtual Method. Use Polymorphism in a Program.

Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you

can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.
Listing 9-1. A Base Class With a Virtual Method: DrawingObject.cs
using System; publicclassDrawingObject { publicvirtualvoid Draw() { Console.WriteLine("I'm just a generic drawing object."); } }

Listing 9-1 shows the DrawingObject class. This will be the base class for other objects to inherit from. It has a single method named Draw(). The Draw() method has a virtual modifier. The virtual modifier indicates to derived classes that they can override this method. The Draw() method of the DrawingObject class performs a single action of printing the statement, "I'm just a generic drawing object.", to the console.
Listing 9-2. Derived Classes With Override Methods: Line.cs, Circle.cs, and Square.cs
using System; publicclass Line : DrawingObject { publicoverridevoid Draw() { Console.WriteLine("I'm a Line."); } } publicclass Circle : DrawingObject { publicoverridevoid Draw() { Console.WriteLine("I'm a Circle."); } } publicclass Square : DrawingObject { publicoverridevoid Draw() { Console.WriteLine("I'm a Square."); } }

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close