C# Simplified, part 4: Structures, Inheritance and Interfaces - Inheritance
(Page 3 of 7 )
Inheritance is the relationship between two or more classes, and is a fundamental concept in every Object Oriented Programming (OOP) language. There will be one class which will act as a base class. The other classes will derive from the base class. This class is termed a derived class. You can call all the variables and methods defined in the base class, in the derived classes. The only condition is that you should declare them as either public or protected. In C#, classes are inherited with the help of the ":" operator.
The following code snippets will help you to understand the concept in more detail.
public class Computer
{
//code goes here
}
class HardDrive:Computer
{
//code goes here
}
class MotherBoard:Computer
{
//code goes here
}
Listing 4.3 defines a class named Computer and a protected method named Calls. The method returns the sum of two numbers. The class HardDrive inherits the base class Computer and calls the method Calls() by creating an object of the derived class.
Listing 4.3
// HardDrive.cs
using System;
class Computer
{
// Erase the Protected modifier and observe the result.
protected void Calls()
{
int num1 = 10;
int num2 = 20;
int num3 = num1+num2;
Console.WriteLine(num3);
}
}
class HardDrive: Computer
{
public static void Main()
{
HardDrive hd = new HardDrive();
hd.Calls();
}
}
C# does not support multiple inheritance. Hence, the following code snippet is not allowed in C#.
Public class Computer: HardDrive, MotherBoard
{
//code goes here
}
In order to rectify the problem caused by multiple inheritance, C# introduces a new concept called interfaces. Interfaces in C# are similar to Java interfaces. You will learn more about interfaces in the final part of this article.
Next: Sealed classes >>
More C# Articles
More By Anand Narayanaswamy