Sunday, June 8, 2014

About abstract class, interfaces, virtual & hiding with new in c sharp

About abstract class, interfaces, virtual & hiding with new in c sharp

Abstract class:

An abstract class is a special type of class that cannot be instantiate. The abstract class is only to be inherited and we can create object for subclasses. In abstract class we can define abstract methods. Abstract members are like virtual members but they don’t provide default implementation. The implementation will be provided by subclass.

Virtual members:

A function marked as the virtual  can be overridden by subclasses wanting to provide a specialized implementation. Not only the methods but also the properties, indexers and events can be declared as can be declared as virtual.

New keyword:

A base class and derived class may have identical members. Then the member in the derived class said to hide the member in the base class.

Example:

public class BaseClass
{
public int counter=1;
}
public class DerivedClass: Baseclass
{
public int counter=5;
}
The counter field in Derived class is said to hide the counter field in the Baseclass. but when compiling a warning will be generated. The warning will be suppressed if we declare subclass member with the new keyword.

Example:

public class BaseClass
{
public int counter=1;
}
public class DerivedClass: Baseclass
{
public new int counter=5;
}

Difference between overriding and hiding with new keyword.

public class BaseClass
{
public virtual void Test()
{
Console.WriteLine(“BaseClass::test”);
}
}
public class DerivedClass: BaseClass
{
public new void Test()
{
Console.writeLine(“DerivedClass::Test”);
}
}
public class overrided: BaseClass
{
public override void Test()
{
Console.WriteLine(“Overrided::Test()”);
}
}

Differences for above classes:

Overrided o=new overrieded();
Baseclass b=o;
o.Test() ;                                            //overrided::test()
b.Test();                                            // overrided::test()

DerivedClass d=new DerivedClass()
BaseClass b=d;
d.Test() ;                                       //DerivedClass::Test()
b.Test();                                         //Baseclass::Test()

 from the above example it is clear that incase of overriding when assigning derived class object to base class object calling to method calls the overrided method. But in case of hiding derived class object when assigning derived class object to base class object calling to method only  calls the base class method.

Interfaces
An interface is not a class. It is an entity that is defined by the word Interface. Interfaces provides the specification rather than an implementation for its members. A class can implement multiple interfaces while a class can inherit only a single class. Interface members are implicitly abstract while a class can provide only abstract members and concrete members with implementations. Struts can implement a class but a struct cannot inherit from a class.