To inherit one class from another, you would use the following syntax: -
class <derivedClass>: <baseClass> -
Here's what this database example would look like: -
using System; class Database { public Database() { CommonField = 42; } public int CommonField; public void CommonMethod() { Console.WriteLine("Database.Common Method"); } } class SQLServer : Database { public void SomeMethodSpecificToSQLServer() { Console.WriteLine("SQLServer.SomeMethodSpecificToSQLServer"); } } class Oracle : Database { public void SomeMethodSpecificToOracle() { Console.WriteLine("Oracle.SomeMethodSpecificToOracle"); } } class InheritanceApp { public static void Main() { SQLServer sqlserver = new SQLServer(); sqlserver.SomeMethodSpecificToSQLServer(); sqlserver.CommonMethod(); Console.WriteLine("Inherited common field = {0}", sqlserver.CommonField); } }
Compiling and executing this application results in the following output: -
SQLServer.SomeMethodSpecificToSQLServer Database.Common Method Inherited common field = 42
Notice that the Database.CommonMethod and Database.CommonField methods are now a part of the SQLServer class's definition. Because the SQLServer and Oracle classes are derived from the base Database class, they both inherit almost all of its members that are defined as public, protected, or internal. The only exception to this is the constructor, which cannot be inherited. Each class must implement its own constructor irrespective of its base class.
Method overriding is covered in Chapter 6. However, for completeness in this section, let me mention that method overriding enables you to inherit a method from a base class and then to change that method's implementation.Abstract classes tie in heavily with method overriding-these too will be covered in Chapter 6.