A class can inherit from another class.
Inheriting from a class can reuse the functionality in that class.
A class can inherit from only a single class.
A derived class is also called a subclass. A base class is also called a superclass.
The following code defines a class called Shape:
class Shape { public string Name; }
Next, we define classes called Circle and Square, which will inherit from Shape.
Circle and Square get everything an Shape has, plus any additional members that they define:
class Circle : Shape // inherits from Shape { public long Radius; } class Square : Shape // inherits from Shape { public decimal Width; }
Here's how we can use these classes:
using System; class MainClass//from www . ja v a 2s . co m { public static void Main(string[] args) { Circle myCircle = new Circle { Name="MyCicle", Radius=1000 }; Console.WriteLine (myCircle.Name); // MyCicle Console.WriteLine (myCircle.Radius); // 1000 Square mySquare = new Square { Name="MySquare", Width=250000 }; Console.WriteLine (mySquare.Name); // MySquare Console.WriteLine (mySquare.Width); // 250000 } } class Circle : Shape // inherits from Shape { public long Radius; } class Square : Shape // inherits from Shape { public decimal Width; } class Shape { public string Name; }
The derived classes, Circle and Square, inherit the Name property from the base class, Shape.