Saturday, 7 April 2012

Basic of Inheritance for beginner

Inheritance is property of oops by which we access one class
into another class without writing the whole code. The class that is inherited
is called base class and the class that does the inheritance is called a
derived class.

Note:- two way of accessing class.1. create the object of
class. 2. Inherit this class.

Syntax for inheritance

Access-modifier class derived-class: base class

{

}

For example

Create base class having one simple method

base_class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

//create base class having one method
for sum

publicclassbase_class

{

publicint sum(int x, int y)

{

return x + y;

}

}

Create derived class which inherited the base class

Derived_Class.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

//create derived class and inherit base
class in it

publicclassDerived_Class: base_class

{

publicint mul(int x, int y)

{

return x * y;

}

//create another method in which call the base class method

publicint
use_base_method(int x, int
y)

{

//use base class method in derived class

int result = sum(x, y);

return result;

}

}

Create the Design page and create the object of derived
class

InheritanceExample.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

publicpartialclassInheritanceExample
: System.Web.UI.Page

{

protectedvoid
Page_Load(object sender, EventArgs e)

{

}

protectedvoid
Button1_Click(object sender, EventArgs e)

{

int fval = Convert.ToInt32(TextBox1.Text);

int sval = Convert.ToInt32(TextBox2.Text);

//create the object of derived class

Derived_Class dc = newDerived_Class();

//sum is method of base class but due to inheritance it can
be accessed

//through the object of derived class

Label1.Text = Convert.ToString(dc.sum(fval,
sval));

//mul is method of derived class

Label2.Text = Convert.ToString(dc.mul(fval,sval));

}

}

Output

In this way we created one base class and define a method. Derived
this class into another class(derived-class). Create the object of derived
class and we can access the member variable and method of both derived and base
class(should be public).