Вы находитесь на странице: 1из 9

Polymorphism

• Polymorphism means same operation may behave differently on different classes.


• Polymorphism allows you to invoke derived class methods through a base class reference during
run-time.
• It has the ability for classes to provide different implementations of methods that are called
through the same name.
Polymorphism is of two types:

1. Compile time polymorphism/Overloading


2. Runtime polymorphism/Overriding

Compile Time Polymorphism


Compile time polymorphism is method and operators overloading. It is also called early
binding.
In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism


Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also called late binding.

When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same prototype.

Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.

P a g e|1
What is Method Overloading (Compile time polymorphism)?

Method overloading allows defining many methods with the same name but with a different set of
parameters .Each combination of parameter types is known as a signature of the method.
When a call is made to one of these overloaded methods, the compiler automatically determines which of
the methods should be used according to the arguments used in the call and the available method
signatures. One of the greatest advantages of method overloading is the improvement that it provides to
code readability and maintainability.

class Calculate
{
public static int Square(int number)
{
Console.WriteLine("Integer Square calculated");
return number * number;
}

public static double Square(double number) Same Name Square with different
{ signature
Console.WriteLine("Double Square calculated");
return number * number;
}

public static double Square(double number, int number1)


{
Console.WriteLine("Two parameter values calculated");
return number * number1;
}
}
static void Main(string[] args)
{
double squareMe = 5;
int squareMeToo = 5;
int sqvalue= 10;
Console.WriteLine(Calculate.Square(squareMe));
Console.WriteLine(Calculate.Square(squareMeToo));
Console.WriteLine(Calculate.Square(squareMeToo,sqvalue));
}
/* OUTPUT
Double Square calculated 25
Integer Square calculated 25
Two parameter values calculated 50
*/

NOTE:
If you were to change the Main method so that the squared variable is a double the code will no longer
compile because the double data type may not be implicitly cast to an integer. In order to support
overloaded method will accept and return doubles rather than integers.
Things to keep in mind while method overloading
1. If you use overload for method, there are couple of restrictions that the compiler imposes.
2. The rule is that overloads must be different in their signature, which means the name and the
number and type of parameters.
3. There is no limit to how many overload of a method you can have. You simply declare them in a
class, just as if they were different methods that happened to have the same name.

P a g e|2
What is Inheritance?
Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse
existing code. In general Classes can be derived from another class such that it inherits all the
members of the base class. The class at the top of the hierarchy is known as the base class and the
derived classes as subclasses. Any number of classes may be derived from a class. It is only possible
for a derived class to inherit from one class. As such, C# is known as a single inheritance
programming language.

Example:
--------------------
Code C# Base (Parent) Class
--------------------
public class baseHello
{
public void sayHello()
{
System.Console.WriteLine("base says hello");
}
} Drive (Child) Class

class derivedHello:baseHello
{
public void sayHello()
{
System.Console.WriteLine("derived says hello");
}
}

--------------------
Code Vb.net
--------------------
Public Class baseHello
Public Sub sayHello()
System.Console.WriteLine("base says hello")
End Sub
End Class

Public Class derivedHello


Inherits baseHello

Public Sub sayHello()


System.Console.WriteLine("derived says hello")
End Sub
End Class

NOTE:
1- In C#, Class is inherited by using “:” in drive class.
2- In VB.Net, Class is inherited by “Inherits” keyword in drive class.
3- A subclass can also inherit from another subclass.

P a g e|3
Virtual Methods in inheritance:
If a base class method is to be overridden, it is defined using the keyword virtual (otherwise
the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but
its usage makes the code more transparent meaningful.
In VB.NET use Overridable not virtual, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class
method is required in a child class along with the overriden method, then the base keyword may be
used to access the parent class member.

Example:

--------------------
Code C#
--------------------
public class baseHello
{
Public virtual void sayHello()
{
System.Console.WriteLine("base says hello");
}
}

class derivedHello:baseHello
{
Public override void sayHello()
{
System.Console.WriteLine("derived says hello");
}
}

--------------------
Code Vb.net
--------------------
Public Class baseHello
Public Overridable Sub sayHello()
System.Console.WriteLine("base says hello")
End Sub
End Class

Public Class derivedHello


Inherits baseHello

Public Overrides Sub sayHello()


System.Console.WriteLine("derived says hello")
End Sub

End Class

This is useful because the compiler verifies that the ‘override’ function has the same signature as the
virtual function.

Note: If the parent class method does not containing the keyword ‘virtual’ and the child class method containing
the ‘override’ key word then it pops up the error message.
'Public Override void sayHello()' cannot override 'Public void sayHello()' because it is not declared 'Virtual'.

P a g e|4
Hiding or shadowing Methods:
In C#, this concept is called Hiding. The new keyword should be used in C#
In VB.NET this concept is called Shadowing. The Shadows keyword should be used in Vb.net
The methods are declared in a child and base class with the same signature but without the key words
virtual and override, the child class function is said to hide the base class function

Shadowing: This is the concept which says, if you have a class (not defined as virtual) which is
already developed by some one else or by you and you need to inherit this class. Problem starts when
existing class having a function with the same name which is already you have in your derived class.
Compiler get confused which function is to be shown when the class is instantiated.
Shadowing hides base class function & derived class’s function is to be shown up.
In VB.net ‘shadow’ keyword is to be used when shadowing a method or any fields. & in c# the new
keyword is used for shadowing the method or any fields.

Example 1:
--------------------
Code C#
--------------------
class someBaseClass
{

}
class abcClass:someBaseClass
{
public int fnAge()
{
return 99;
}
}
class grandchildClass: abcClass
{
public int fnAge()
{
return 10;
}
}
--------------------
Code Vb.net
--------------------
Public Class someBaseClass

End Class
Public Class abcClass
Inherits someBaseClass
Public Function fnAge() As Int16
Return 99
End Function
End Class
Public Class grandchildClass
Inherits abcClass
Public Function fnAge() As Int16
Return 10
End Function
End Class
NOTE: If u has not write ‘new’ or ‘shadows’ keyword then the compiler will not give
any error. It just gives a warning message and performs shadowing automatically.

P a g e|5
In the example above the function fnAge in grandChildClass hides the function fnAge in its parent
class ie abcClass

The C# or VB.net compiler will generate a warning in this case The ‘new’ or ‘shadows’ keyword should
be used when we intend to hide a method

Example:

Example 2:
--------------------
Code C#
--------------------
class grandchildClass: abcClass
Hiding Method
{
public new int fnAge()
{
return 10;
}
}
--------------------
Code Vb.net
--------------------
Public Class grandchildClass Shadowing Method
Inherits abcClass
Public Shadows Function fnAge() As Int16
Return 10
End Function
End Class

Criterion Shadowing Overriding


Purpose Protecting against a subsequent base class Achieving polymorphism by defining a
modification introducing a member you different implementation of a procedure or
have already defined in your derived class property with the same calling sequence
Redefined element Any declared element type Only a procedure (Function or Sub) or
property
Redefining element Any declared element type Only a procedure or property with the
identical calling sequence1
Accessibility Any accessibility Cannot expand the accessibility of
overridden element (for example cannot
override Protected with Public)
Readability and writability Any combination Cannot change readability or writability of
overridden property
Keyword usage Shadows recommended in derived class; Overridable required in base class;
Shadows assumed if neither Shadows nor Overrides required in derived class
Overrides specified
Inheritance of redefining Shadowing element inherited by further Overriding element inherited by further
element by classes deriving derived classes; shadowed element still derived classes; overridden element still
from your derived class hidden2 overridden

P a g e|6
Calling Functions from the Base Class in drive class:
In C#, To call a function from the base class simply use the keyword base
In VB.Net, To call a function from the base class simply use ”base class function name”.

Example :
--------------------
Code C#
--------------------
class someBaseClass
{

}
class abcClass:someBaseClass
{
public int fnAge()
{
return 99;
}
public int fnAge1()
{
return 99;
}
}
class grandchildClass: abcClass
{
public int fnAge()
{ Note it.
int intValue;
intValue = base.fnAge1();
return 10 + intValue;
}
}
--------------------
Code Vb.net
--------------------

Public Class someBaseClass


Public Function ParentMethod1()
Return 78
End Function
End Class

Public Class abcClass


Inherits someBaseClass
Public Function fnAge() As Int16 Note it.
ParentMethod1()
Return 99
End Function
End Class

P a g e|7
Use the Constructor in inheritance:
1- Use the Constructor in Base & drive class.

Example :
--------------------
Code C#
--------------------
public class ParentClass Base class Constructor
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}

public class ChildClass : ParentClass Child class Constructor


{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}

public static void Main()


{
ChildClass child = new ChildClass();
child.print();
}
}
Output: Parent Constructor. Child Constructor.I'm a Parent Class.
--------------------
Code VB.Net
--------------------
Base class Constructor
Public Class ParentClass
Sub New()
Console.WriteLine("Parent Constructor.")
End Sub

Public Sub print()


Console.WriteLine("I'm a Parent Class.")
End Sub
End Class
Public Class ChildClass
Inherits ParentClass Child class Constructor
Sub New()
Console.WriteLine("Child Constructor.")
End Sub
Public Sub Main()
Dim child As New ChildClass
child.print()
End Sub
End Class

P a g e|8
2- Use only drive class Constructor . & call parent method at instantiation

Example :
--------------------
Code C#
--------------------
public class Parent
{
string parentString; Base class Constructor
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
} Skip the base class Constructor
}
public class Child : Parent
{
public Child() : base("From Derived")
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
public static void Main()
{
Child child = new Child();
child.print();
((Parent)child).print();
}
} It calls parent method. Parent is Keyword.

Output:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.

If the code had not appended base ("From Derived") to the Derived constructor, the code would have automatically
called Parent(). The first line of output shows the base class constructor being called with the string "From Derived".

P a g e|9

Вам также может понравиться