Introduction
Inheritance helps us reuse code and organize related things easily. It lets one class get features from another, so we don't repeat ourselves.
Jump into concepts and practice - no test required
Inheritance helps us reuse code and organize related things easily. It lets one class get features from another, so we don't repeat ourselves.
class BaseClass { // common features } class DerivedClass : BaseClass { // extra features }
The DerivedClass inherits all features from BaseClass.
Use : to show inheritance in C#.
class Animal { public void Eat() { Console.WriteLine("Eating food"); } } class Dog : Animal { public void Bark() { Console.WriteLine("Barking"); } }
class Vehicle { public void Start() { Console.WriteLine("Starting vehicle"); } } class Car : Vehicle { public void Honk() { Console.WriteLine("Honking horn"); } }
This program shows how Dog inherits Eat() from Animal and also has its own Bark() method.
using System; class Animal { public void Eat() { Console.WriteLine("Eating food"); } } class Dog : Animal { public void Bark() { Console.WriteLine("Barking"); } } class Program { static void Main() { Dog myDog = new Dog(); myDog.Eat(); // inherited method myDog.Bark(); // own method } }
Inheritance helps avoid repeating the same code in multiple classes.
Derived classes can use and add to the features of base classes.
Use inheritance carefully to keep code simple and clear.
Inheritance lets one class get features from another to reuse code.
It helps organize related classes and add new features easily.
Use inheritance to write cleaner and more maintainable code.
Animal in C#?class Child : Parent { }.class Animal { public void Speak() { Console.WriteLine("Animal speaks"); } }
class Dog : Animal { public void Bark() { Console.WriteLine("Dog barks"); } }
var d = new Dog();
d.Speak();class Vehicle { public void Move() { Console.WriteLine("Moving"); } }
class Car Vehicle { public void Honk() { Console.WriteLine("Honk!"); } }ElectricCar that has all features of Car plus a new method ChargeBattery(). Which is the best way to do this using inheritance?