In C#, inheritance is the process by which one class inherits the members of another class. The class that inherits is called a subclass or derived class. The other class is called a superclass, or a base class.
When you define a class that inherits from another class, the derived class implicitly gains all the members of the base class, except for its constructors. The derived class can thereby reuse the code in the base class without having to re-implement it. In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.
public class Horse : Animal{ }// inheritance uses colon syntax to denote a class inherits from a superclass. In this case, the Horse class inherits from the Animal class.// A derived class can only inherit from one base class, but inheritance is transitive. That base class may inherit from another class, and so on, which creates an inheritance hierarchy.
In C#, a derived class (subclass) can modify the behavior of an inherited method. The method in the derived class must be labeled override
and the method in the base class (superclass) must be labeled virtual
.
The virtual
and override
keywords are useful for two reasons:
class BaseClass{public virtual void Method1(){Console.WriteLine("Base - Method1");}}class DerivedClass : BaseClass{public override void Method1(){Console.WriteLine("Derived - Method1"); }}
In C#, a protected member can be accessed by the current class and any class that inherits from it. This is designated by the protected
access modifier.
public class BankAccount{private int accountNumber = 12345678;protected decimal balance = 0;public string bankName = "Codecademy Bank";}public class StudentAccount : BankAccount{}// In this example, only BankAccount can access accountNumber, since it is private// both BankAccount and StudentAccount have access to the balance field, since it is protected// and any class would be able to access bankName, as it is public