As you know Polymorphism is the concepts of OOPS which
includes method overriding and method overloading. Virtual and Override keyword
are used for method overloading and new keyword is used for method hiding.
Let's have look on these keywords in C# and try to understand each importance.
Simple Class Inheritance
Consider the below class hierarchy with classes A, B and
C. A is the super/base class, B is derived from class A and C is derived from
class B.
If a method Test() is declared in the base class A and
classes B or C has no methods as shown below.
using
System;
namespace
Polymorphism
{
class A
{
public void Test() {
Console.WriteLine("A::Test()"); }
}
class B : A { }
class C : B { }
class Program
{
static void
Main(string[] args)
{
A a = new A();
a.Test(); //
output --> "A::Test()"
B b = new B();
b.Test(); //
output --> "A::Test()"
C c = new C();
c.Test(); //
output --> "A::Test()"
Console.ReadKey();
}
}
}
Suppose you have Test() method in all the classes A, B, C
as shown below:
using
System;
namespace
Polymorphism
{
class A
{
public void Test() {
Console.WriteLine("A::Test()"); }
}
class B : A
{
public void Test() {
Console.WriteLine("B::Test()"); }
}
class C : B
{
public void Test() {
Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output -->
"A::Test()"
b.Test(); // output -->
"B::Test()"
c.Test(); // output -->
"C::Test()"
a = new B();
a.Test(); // output -->
"A::Test()"
b = new C();
b.Test(); // output -->
"B::Test()"
Console.ReadKey();
}
}
}
When you will run the above program, it will run
successfully and gives the O/P. But this program will show the two warnings as
shown below:
'Polymorphism.B.Test()' hides inherited member
'Polymorphism.A.Test()'. Use the new keyword if hiding was intended.
'Polymorphism.C.Test()' hides inherited member
'Polymorphism.B.Test()'. Use the new keyword if hiding was intended.
Method Hiding (new
keyword)
As you have seen in the above example the compiler
generate the warnings since C# also supports method hiding. For hiding the base
class method from derived class simply declare the derived class method with
new keyword. Hence above code can be re-written as :
using
System;
namespace
Polymorphism
{
class A
{
public void Test() {
Console.WriteLine("A::Test()"); }
}
class B : A
{
public new void Test() {
Console.WriteLine("B::Test()"); }
}
class C : B
{
public new void Test() {
Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output -->
"A::Test()"
b.Test(); // output -->
"B::Test()"
c.Test(); // output -->
"C::Test()"
a = new B();
a.Test(); // output --> "A::Test()"
b = new C();
b.Test(); // output -->
"B::Test()"
Console.ReadKey();
}
}
}
Moreover, if you are expecting the fourth and fifth
output should be "B::Foo()" and "C::Foo()" since the
objects a and b are referenced by the object of B and C respectively then you
have to re-write the above code for Method Overriding.
Method Overriding (virtual
and override keyword)
In C#, for overriding the base class method in derived
class, you have to declare base class method as virtual and derived class
method as override as shown below:
using
System;
namespace
Polymorphism
{
class A
{
public virtual void Test() {
Console.WriteLine("A::Test()"); }
}
class B : A
{
public override void Test() {
Console.WriteLine("B::Test()"); }
}
class C : B
{
public override void Test() {
Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output -->
"A::Test()"
b.Test(); // output -->
"B::Test()"
c.Test(); // output -->
"C::Test()"
a = new B();
a.Test(); // output -->
"B::Test()"
b = new C();
b.Test(); // output -->
"C::Test()"
Console.ReadKey();
}
}
}
Mixing Method Overriding
and Method Hiding
You can also mix the method hiding and method overriding
by using virtual and new keyword since the method of a derived class can be
virtual and new at the same time. This is required when you want to further
override the derived class method into next level as I am overriding Class B,
Test() method in Class C as shown below:
using
System;
namespace
Polymorphism
{
class A
{
public void Test() {
Console.WriteLine("A::Test()"); }
}
class B : A
{
public new virtual void Test() {
Console.WriteLine("B::Test()"); }
}
class C : B
{
public override void Test() {
Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output -->
"A::Test()"
b.Test(); // output -->
"B::Test()"
c.Test(); // output -->
"C::Test()"
a = new B();
a.Test(); // output -->
"A::Test()"
b = new C();
b.Test(); // output -->
"C::Test()"
Console.ReadKey();
}
}
}
Note
The virtual keyword is used to modify a method, property,
indexer, or event declared in the base class and allow it to be overridden in
the derived class.
The override keyword is used to extend or modify a
virtual/abstract method, property, indexer, or event of base class into derived
class.
The new keyword is used to hide a method, property,
indexer, or event of base class into derived class.
Difference between Encapsulation and Abstraction in OOPS
Abstraction and
Encapsulation are two important Object Oriented Programming (OOPS)
concepts. Encapsulation and Abstraction both are interrelated terms.
Real Life Difference Between Encapsulation and Abstraction
Encapsulate
means to hide. Encapsulation is also called data hiding.You can think
Encapsulation like a capsule (medicine tablet) which hides medicine
inside it. Encapsulation is wrapping, just hiding properties and
methods. Encapsulation is used for hide the code and data in a single
unit to protect the data from the outside the world. Class is the best
example of encapsulation.
Abstraction
refers to showing only the necessary details to the intended user. As
the name suggests, abstraction is the "abstract form of anything". We
use abstraction in programming languages to make abstract class.
Abstract class represents abstract view of methods and properties of
class.
Implementation Difference Between Encapsulation and Abstraction
1. Abstraction
is implemented using interface and abstract class while Encapsulation
is implemented using private and protected access modifier.
2. OOPS
makes use of encapsulation to enforce the integrity of a type (i.e. to
make sure data is used in an appropriate manner) by preventing
programmers from accessing data in a non-intended manner. Through
encapsulation, only a predetermined group of functions can access the
data. The collective term for datatypes and operations (methods) bundled
together with access restrictions (public/private, etc.) is a class.
3. Example of Encapsulation
Class Encapsulation
{
private int marks;
public int Marks
{
get { return marks; }
set { marks = value;}
}
}
4. Example of Abstraction
abstract class Abstraction
{
public abstract void doAbstraction();
}
public class AbstractionImpl: Abstraction
{
public void doAbstraction()
{
//Implement it
}
}
Abstraction - hiding implementation.
encapsulation - hiding data.
Abstract classes
Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
An abstract class is denoted in Visual Basic by the keyword MustInherit. In C#, the abstract modifier is used. Any methods that are meant to be invariant may be coded into the base class, but any methods that are to be implemented are marked in Visual Basic with the MustOverride modifier. In C#, the methods are marked abstract. The following example shows an abstract class:
encapsulation - hiding data.
Abstract classes
Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
An abstract class is denoted in Visual Basic by the keyword MustInherit. In C#, the abstract modifier is used. Any methods that are meant to be invariant may be coded into the base class, but any methods that are to be implemented are marked in Visual Basic with the MustOverride modifier. In C#, the methods are marked abstract. The following example shows an abstract class:
'
Visual Basic
Public
MustInherit Class WashingMachine
Sub New()
' Code to instantiate the class goes
here.
End sub
Public MustOverride Sub Wash
Public MustOverride Sub Rinse (loadSize as
Integer)
Public MustOverride Function Spin (speed as
Integer) as Long
End
Class
//
C#
abstract
class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes
here.
}
abstract public void Wash();
abstract public void Rinse(int loadSize);
abstract public long Spin(int speed);
}
' Visual Basic
Public Class MyWashingMachine
Inherits WashingMachine
Public Overrides Sub Wash()
' Wash code goes here
End Sub
Public Overrides Sub Rinse (loadSize as Integer)
' Rinse code goes here
End Sub
Public Overrides Function Spin (speed as Integer) as Long
' Spin code goes here
End Sub
End Class
// C#
class MyWashingMachine : WashingMachine
{
public MyWashingMachine()
{
// Initialization code goes here.
}
override public void Wash()
{
// Wash code goes here.
}
override public void Rinse(int loadSize)
{
// Rinse code goes here.
}
override public long Spin(int speed)
{
// Spin code goes here.
}
}
When implementing an abstract class, you must implement each abstract (MustOverride)
method in that class, and each implemented method must receive the same number
and type of arguments, and have the same return value, as the method specified
in the abstract class.
The abstract keyword enables you to create classes
and class members that are incomplete and must be
implemented in a derived class.
The sealed keyword enables you to prevent the
inheritance of a class or certain class members that were previously marked virtual.
Classes can be declared as abstract
by putting the keyword abstract before the class definition. For example:
C#
public abstract class A
{
// Class members here.
}
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. For
example, a class library may define an abstract class that is used as a
parameter to many of its functions, and require programmers using that library
to provide their own implementation of the class by creating a derived class.
Abstract classes may also define
abstract methods. This is accomplished by adding the keyword abstract before
the return type of the method. For example:
C#
public abstract class A
{
public abstract void DoWork(int i);
}
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. For example:
C#
// compile with: /target:library
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract,
it is still virtual to any class inheriting from the abstract class. A class
inheriting an abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork on class
D. In this way, an abstract class can force derived classes to provide new
method implementations for virtual methods.
Classes can be declared as sealed by putting the keyword sealed before the
class definition. For example:
C#
public sealed class D
{
// Class members here.
}
A sealed class cannot be used as a
base class. For this reason, it cannot also be an abstract class. Sealed
classes prevent derivation. Because they can never be used as a base class,
some run-time optimizations can make calling sealed class members slightly
faster.
A method, indexer, property, or
event, on a derived class that is overriding a virtual member of the base class
can declare that member as sealed. This negates the virtual aspect of the
member for any further derived class. This is accomplished by putting the sealed
keyword before the override keyword in the class member declaration.
For example:
C#
public class D : C
{
public sealed override void DoWork() { }
}
Very Nice Article
ReplyDelete