English speaking and learning Interview Questions and Answers Programs C# Concept OOPS Concept JOBS

Saturday, February 25, 2017

Inheritance in OOPS

Inheritance is a mechanism in which Derived class gets behavior of base class.in simple words,Child class acquires feature and behavior of parent class.
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Base class cannot be private.

The new class—the derived class—then gains all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself. If parent class has private member variable,child class cannot access it.
I have a parent class.It has constructor,2 member variable and function.

    class Parent
        private int parent;
        public int parent2;

        public Parent()
            Console.WriteLine("parent constructor");


        public void ParentMethod()
            Console.WriteLine("Hello from parent method");


Child class inherited parent class

class child : Parent
        public void ChildMethod()
            Console.WriteLine("Hello from child method");

        public child()
            Console.WriteLine("child constructor");



In screenshot, you can see that object of  child class can not access private variable parent.
it can only access public variable and function of parent class.

Program class

   class Program
        static void Main(string[] args)
            child c = new child();

The new class then has two effective types: the type of the new class and the type of the class it inherits.

The benefit of inheritance is that the child class doesn't have to redeclare and redefine all the members which it inherits from the parent class. It is therefore a way to re-use code. 

 static class can not inherited it.Inheritance means to communicate object to object,not class to class.

If there is constructor in base class and on constructor in derived class,base class constructor called first.

in screen shot,you can see the output.

If class is sealed,no one can inherit it.means,Class do not want to go for extensibility.Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class. Advantages
1)Provides code re usability.
2)Reduces source code size and improves code readability.
3)Code is easy to manage and divided into parent and child classes.

1)In Inheritance base class and child classes are not loosely coupled .they are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes.

2)many data members of parent class remain unused and the memory allocated to them is not utilized. Hence affect performance of your program if you have not implemented inheritance properly.

You will also like it.

No comments :

Post a Comment