Inheritance is the ability to define a new class or object that inherits the behavior and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class.
In other words when a class acquire the property of another class is known as inheritance.We can say that, inheritance is the second pillar of OOPs because with the help of single class we can’t make our project. Through inheritance we can achieve code reusability and encapsulation.
For example, I have created a Shape class as a Parent class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OopsConcepts { classShape { protectedint width; protectedint height; publicvoid setWidth(int w) { width = w; } publicvoid setHeight(int h) { height = h; } } }
Here I havecreating an another class Rectangle that inherit to Shape class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OopsConcepts { classRectangle:Shape { publicint getArea() { return(width * height); } publicint getPerimeter() { return2*(width + height); } } }
And create another entry point class (RectangleTest) and which we are creating
object of the Rectangle class for calling the method of their respective class.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OoopsConcepts { classRectangleTest { staticvoid Main(string[] args) { // Inhertance Test Rectangle rectange = newRectangle();
rectangle.setWidth(10); rectangle.setHeight(5); Console.WriteLine("Total area : {0}", rectangle.getArea()); Console.WriteLine("Perimeter : {0}", rectangle.getPerimeter()); Console.ReadLine(); } } }
Output:
Total area: 50
Perimeter: 30
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Inheritance:
Inheritance is the ability to define a new class or object that inherits the behavior and its functionality of an existing class. The new class or object is called a child or subclass or derived class while the original class is called parent or base class.
In other words when a class acquire the property of another class is known as inheritance.We can say that, inheritance is the second pillar of OOPs because with the help of single class we can’t make our project. Through inheritance we can achieve code reusability and encapsulation.
For example, I have created a Shape class as a Parent class
And create another entry point class (RectangleTest) and which we are creating
object of the Rectangle class for calling the method of their respective class.
Output:
Total area: 50
Perimeter: 30