Sunday 11 September 2011

Abstract Classes (Virtual Class)

Actually in some situation the classes are required only for inheritance, such type
of classes are called Abstract classes. This concept is very useful when
creating a framework for the applications where there will not be any
implementation for the methods and properties in the abstract class. It just
defines the structure.
Abstract classes are declared using MustInherit and MustOverride keyword.

Syntax:-

Public MustInherit Class AbstractBaseClass
Public MustOverride Sub DoSomething()
Public MustOverride Sub DoOtherStuff()
End Class
public abstract class AbstractBaseClass
{
public abstract void DoSomething();
public abstract void DoOtherStuff();
}
MustInherit keyword is used with the class name, where as MustOverride
keyword is used with the members of the class.
Implementaion:-
Public Class DerivedClass
Inherits AbstractBaseClass
Public Overrides Sub DoSomething()
MsgBox("This method is overrides the Base class DoSomething to implement the
method functionality”)
End Sub
Public Overrides Sub DoOtherStuff()
MsgBox(“This method is overrides the Base class DoOtherStuff to implement the
method functionality”)
End Sub
End Class
public class DerivedClass : AbstractBaseClass
{
public Override void DoSomething()
{
MessagegBox.Show("This method is overrides the Base class DoSomething to
implement the method functionality”);
}
public Override void DoOtherStuff()
{
MessaggeBox.Show(“This method is overrides the Base class DoOtherStuff to
implement the method functionality”);
}
}


MustInherit forces the classes to be inherited from the derived class and write
an implementation code for the methods and properties in the derived class
before using it.
As in the above example, any class that inherits AbstractBaseClass must
implement the Dosomething and DoOtherStuff methods.
We cannot create an instance of the AbstractBaseClass as shown below.
 
Dim obj as New AbstractBaseClass()
‘Error in Decleration
AbstractBaseClass obj = new AbstractBaseClass()
‘Error in Decleration

No comments:

Post a Comment