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
Syntax of Inheritance
Access-modifier class derived-class: base class{ }
Create base class having one simple method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//create base class having one method for sum
public class base_class
{
public int sum(int x, int y)
{
return x + y;
}
}
Create derived class which inherited the base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//create derived class and derive base class in it
public class Derived_Class: base_class
{
public int mul(int x, int y)
{
return x * y;
}
//create another method in which call the base class method
public int use_base_method(int x, int y)
{
//use base class method in derived class
int result = sum(x, y);
return result;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class InheritanceExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e){ }
protected void 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 = new Derived_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));
}
}
Figure 1
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).
For any query you can send mail at info@techaltum.com
Thanks