C# Class Inheritance
In this chapter you will learn:
- What is Inheritance
- Syntax for Class Inheritance
- Example for Class Inheritance
- 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:
- What is base keyword
- Using base to Access a Hidden Name
- Example for C# base Keyword
- Call constructor in base class
- A demo showing what is name hiding
- How to use base to reference parent class
- How to call a hiddel method from parent class