Wednesday, February 1, 2012

how to use the abstract class in asp.net

The class under which we define the abstract methods is an abstract class.Abstract class has to be declared using "abstract" keyword.
abstract class example
{
public abstract void test();
}
An abstract class can contain both abstract and non abstract methods in it.Each and every abstract method which was declared under the abstract class should be given implementation with in the child class or child cannot utilize non abstract methods of the parent.An abstract class is not usable for it self because the object of an abstract class can't be created using "new" operator.It can be utilized only by the child class after giving the implementation for abstract methods of parent.If the child class doesn't provide the implementation for the abstract methods in its parent child also becomes abstract.
Example:
abstract class parent
{
public int add(int a,int b)
{
return a+b;
}
public int sud(int a,int b)
{
return a-b;
}
public abstract int mul(int a,int b);
public abstract int div(int a,int b);
}
//Add one more class child.cs

class child:parent
{
public override int mul(int a,int b)
{
return a/b;
}
public void test()
{
Console.Writeline("child method");
}
static void menu()
{
child c=new child();
Console.Writeline(c.add(2,3));
Console.Writeline(c.sub(2,3));
Console.Writeline(c.mul(2,3));
Console.Writeline(c.div(2,3));
c.Test();
console.Readline()
}
}
The object of an abstract can be created by assigning the object of it's class to it's variable,using this object every method declared and implemented under the abstract class can be called.Here the following code under the main methods of child class
Note:In derived class i have override the mul() method
parent p=new child();
Console.Writeline(p.add(2,3));
Console.Writeline(p.sub(2,3));
Console.Writeline(p.mul(2,3));
Console.Writeline(p.div(2,3));
//c.Test();//invalid
console.Readline()

No comments:

Bel