Thursday, 13 October 2016

Inheritance


Inheritance is the feature of the .Net framework , which allow to create a new class with all the member of previously defined class .For example ,we have defined class A ,, now inherited class B . All member of class A will come to Clasas B automatically.The first class is called Base class an second class is called derived class . In other object oriented programming language allow unlimited level of inheritance  , but .Net frame work allow only 2nd level inheritance . The main advantage of inheritance is just copy/implement common functionality of Base class to derived clasas . Now I am creating an class
public class parent //base class
{
    public int public_member;
    public int public_method(int a, int b)
    {
        return (a + b);
    }
}

public class child : parent
{
    //derived class
}

Notice that , child class do not have any method .Now I am creating instance of the clind class.
        child obj = new child();

obj.public_member;
obj.public_method();
We get both member of the parent class in child class . Noticed that , member of the parent class declared public ,so that we can inherit it , only public , protected access modifier will be available during Inheritance .Here is an example ,

public class Parent
{
    private void Method1()
    {
    }
    protected void Method2()
    {
    }

}

public class child : Parent
{
    public void method_call()
    {
        this.method1();//compliler through error-inacccable due to protection level
        this.Method2.method2();//will compile & work
    }
}

Is there any way , that we can define a class that can not be Inherited ?
Yes . there is , the keyword called “sealed” , seal keyword tells compiler that , this class can not be inherted  . For example
public sealed class  Myclass
{

}
Now , I am trying to Inherit the clasas “MyClasas”
public class MyChild : Myclass
{
}
//error MyChild': cannot derive from sealed type 'Myclass'

An error will shown , sealed class can not be inherited , but we can create instance of the seal class .The question is , what is the use of sealed class ?
Sealed class is mainly used for security features, so that class cannot be modified.

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...