Hello everyone,
Kindly explain "What is the use of Inheritance? and When to use?" with respect two below programs.
Why I cannot get output from 1st program after using class initialization?
Program 1:
- class Program
- {
- class Shape
- {
- public void setWidth(int w)
- {
- width = w;
- }
- public void setHeight(int h)
- {
- height = h;
- }
- public int width;
- public int height;
- }
- // Derived class
- class Rectangle
- {
- Shape objshape = new Shape();
- public int getArea()
- {
- return (objshape.width * objshape.height);
- }
- }
- static void Main(string[] args)
- {
- Shape Rect = new Shape();
- Rectangle objRectangle = new Rectangle();
- Rect.setWidth(5);
- Rect.setHeight(7);
- // Print the area of the object.
- Console.WriteLine("Total area: {0}", objRectangle.getArea());
- Console.ReadKey();
- }
- }
Program 2:
- class Program
- {
- class Shape
- {
- public void setWidth(int w)
- {
- width = w;
- }
- public void setHeight(int h)
- {
- height = h;
- }
- public int width;
- public int height;
- }
- // Derived class
- class Rectangle : Shape
- {
- public int getArea()
- {
- return (width * height);
- }
- }
- static void Main(string[] args)
- {
- Rectangle Rect = new Rectangle();
- Rect.setWidth(5);
- Rect.setHeight(7);
- // Print the area of the object.
- Console.WriteLine("Total area: {0}", Rect.getArea());
- Console.ReadKey();
- }
- }

Bikesh SrivastavaPosted Sep 12, 2016, 2:25 AM
Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass
Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class
Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.