C# Class Inheritance

In this chapter you will learn:

  1. What is Inheritance
  2. Syntax for Class Inheritance
  3. Example for Class Inheritance
  4. Note for Class Inheritance

Description

Classes (but not structs) support the concept of inheritance. A class that derives from the base class automatically has all the public, protected, and internal members of the base class except its constructors and destructors.

A class can inherit from another class to extend the original class.

Inheriting from a class lets you reuse the functionality in that class.

A class can inherit from only a single class.

Syntax

The general form of a class declaration that inherits a base class:


class derived-class-name : base-class-name {
    // body of class
} 

Example

In this example, we start by defining a class called Shape:


public class Shape { 
  public string Name; 
} 

Next, we define classes called Circle and Rectangle, which will inherit from Shape. They get everything an Shape has, plus any additional members that they define:


public class Circle : Shape   // inherits from Shape 
{ /*w  w w . j  a va2s  .c  o m*/
  public long Radius; 
} 

public class Rectangle : Shape   // inherits from Shape 
{ 
  public decimal Width; 
} 

Here's how we can use these classes:

                                          
Circle myCircle = new Circle { Name="Circle", 
                         Radius=1000 }; 
//from  ww w  .  jav  a2s. c  om
Console.WriteLine (myCircle.Name);       
Console.WriteLine (myCircle.Radius); 

Rectangle myRect = new Rectangle { Name="Rectangle",                                                    
                            Width=250000 };                                                 

Console.WriteLine (myRect.Name);                                              
Console.WriteLine (myRect.Width);   

The subclasses, Circle and Rectangle, inherit the Name property from the base class, Shape.

Note

A subclass is also called a derived class. A base class is also called a superclass.

Next chapter...

What you will learn in the next chapter:

  1. What is base keyword
  2. Using base to Access a Hidden Name
  3. Example for C# base Keyword
  4. Call constructor in base class
  5. A demo showing what is name hiding
  6. How to use base to reference parent class
  7. How to call a hiddel method from parent class
Home »
  C# Tutorial »
    C# Types »
      C# Inheritance
C# Class Inheritance
C# base Keyword
C# seal Functions and Classes
C# Abstract Classes and Abstract Members
C# Polymorphism
C# Virtual Function Members
C# Override methods
C# Shadow inherited members
C# as operator
C# is operator