For Asp.net Training with C# Click Here
Written By:-Isha Malhotra
Email:-malhotra.isha3388@gmail.com
Basic
of Inheritance for beginners
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
public class base_class
{
public int 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
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;
}
}
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;
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));
}
}
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).
Nice work!!
ReplyDeletethanks!!
DeleteThis comment has been removed by the author.
ReplyDelete