C# | Inheritance in Constructors
Last Updated :
06 Apr, 2023
Introduction:
Inheritance in constructors is a feature in C# that allows a derived class to inherit the constructor of its base class. This means that the derived class can use the constructor of the base class to initialize its own fields and properties. This feature saves a lot of code duplication and makes it easier to create derived classes that are closely related to their base classes.
Advantages:
- Code reuse: Inheritance in constructors enables the derived class to reuse the constructor of the base class, saving a lot of code duplication and making the code more concise.
- Saves time: Inheritance in constructors saves time as developers don’t have to write the same code again and again.
- Easy to maintain: Inheritance in constructors makes it easier to maintain the code as changes made in the base class constructor are automatically inherited by the derived class constructors.
Disadvantages:
- Tight coupling: Inheritance in constructors can lead to tight coupling between the base class and the derived class, making it difficult to modify the base class without affecting the derived class.
- Complexity: Inheritance in constructors can make the code more complex and harder to understand, especially if there are multiple levels of inheritance.
Reference books:
- “C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET using Visual Studio Code, 4th Edition” by Mark J. Price
- “C# in Depth, 4th Edition” by Jon Skeet
- “Head First C#: A Learner’s Guide to Real-World Programming with C#, XAML, and .NET” by Andrew Stellman and Jennifer Greene
In C#, when we use inheritance, we can also inherit the constructors of the base class. This can be useful in situations where we want to reuse the code of the base class constructor in the derived class constructor.
To inherit a constructor from the base class, we use the base keyword followed by the parameter list of the base class constructor. The base keyword refers to the constructor of the base class.
Here is an example:
C#
using System;
class Vehicle
{
public int speed;
public Vehicle( int speed)
{
this .speed = speed;
}
}
class Car : Vehicle
{
public string model;
public Car( int speed, string model) : base (speed)
{
this .model = model;
}
}
class Program
{
static void Main( string [] args)
{
Car car = new Car(60, "Toyota" );
Console.WriteLine( "Car Model: {0}, Speed: {1}" , car.model, car.speed);
}
}
|
Output
Car Model: Toyota, Speed: 60
In the example above, we have a Vehicle class with a constructor that takes an int parameter for the speed. We then have a Car class that inherits from the Vehicle class and has an additional property for the model. The Car class constructor uses the base keyword to inherit the Vehicle class constructor, passing in the speed parameter. The model parameter is then assigned to the model property of the Car class.
When we create an instance of the Car class and pass in values for the speed and model parameters, the Car class constructor calls the Vehicle class constructor using the base keyword, passing in the speed parameter. The model parameter is then assigned to the model property of the Car class. Finally, we print out the model and speed properties of the car object.
In C#, both the base class and the derived class can have their own constructor. The constructor of a base class used to instantiate the objects of the base class and the constructor of the derived class used to instantiate the object of the derived class. In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class. Instead of inheriting constructors by the derived class, it is only allowed to invoke the constructor of base class. In C#, when we are working with the constructor in inheritance there are two different cases arise as follows: Case 1: In this case, only derived class contains a constructor. So the objects of the derived class are instantiated by that constructor and the objects of the base class are instantiated automatically by the default constructor. Example:
CSharp
using System;
class Tank {
double t_radius;
double t_height;
public double Radius
{
get {
return t_radius;
}
set {
t_radius = value < 0 ? -value : value;
}
}
public double Height
{
get {
return t_height;
}
set {
t_height = value < 0 ? -value : value;
}
}
public void DisplayDimension()
{
Console.WriteLine("The radius of tank is :" + Radius
+ " and the height of tank is :" + Height);
}
}
class AreaOfTank : Tank {
string Color;
public AreaOfTank( string c, double r, double h)
{
Radius = r;
Height = h;
Color = c;
}
public double Area()
{
return 2 * 3.14 * Radius * Height;
}
public void DisplayColor()
{
Console.WriteLine("The Color of tank is "
+ Color);
}
}
class GFG {
static void Main()
{
AreaOfTank t1 = new AreaOfTank("Green", 6.0, 12.0);
t1.DisplayColor();
t1.DisplayDimension();
Console.WriteLine("Area is " + t1.Area());
}
}
|
Explanation: In the above example Tank is the base class and AreaOfTank is the derived class. Tank class provides the dimensions of the tank and AreaOfTank provides the color and the area of the tank. And Tank class does not contain any constructor so the default constructor is used to instantiate the object of class and AreaOfTank class contains AreaOfTank() constructor which instantiate the object of class. Case 2: In this case, both the base class and derived class has their own constructors, so the process is complicated because the constructors of both classes must be executed. To overcome this situation C# provide a keyword known as a base keyword. With the help of base keyword, the derived class can call the constructor which is defined in its base class. Note: Any form of the constructor defined in the base class can be called by the base keyword, but only that constructor executes that matches the arguments. Syntax:
derived-constructor(parameter-list) : base(argument-list)
{
// body of constructor
}
Here, argument-list contains arguments that are required by the constructor of the base class. Example:
CSharp
using System;
class Tank {
double t_radius;
double t_height;
public Tank( double r, double h)
{
Radius = r;
Height = h;
}
public double Radius
{
get {
return t_radius;
}
set {
t_radius = value < 0 ? -value : value;
}
}
public double Height
{
get {
return t_height;
}
set {
t_height = value < 0 ? -value : value;
}
}
public void DisplayDimension()
{
Console.WriteLine("The radius of tank is :" + Radius
+ " and the height of tank is :" + Height);
}
}
class AreaOfTank : Tank {
string Color;
public AreaOfTank( string c, double r,
double h) : base (r, h)
{
Color = c;
}
public double Area()
{
return 2 * 3.14 * Radius * Height;
}
public void DisplayColor()
{
Console.WriteLine("The Color of tank is " + Color);
}
}
class GFG {
static void Main()
{
AreaOfTank t1 = new AreaOfTank("Brown", 4.0, 8.0);
t1.DisplayColor();
t1.DisplayDimension();
Console.WriteLine("Area is " + t1.Area());
}
}
|
Explanation: In the above example, Tank is the base class and AreaOfTank is the derived class. The Tank class describes the dimension of the tank and AreaOfTank describe the color and the area of the tank. Both the base class and the derived class have their own constructor. But we declare the constructor of AreaOfTank with a base keyword as shown here:
public AreaOfTank(string c, double r, double h) : base (r, h)
{
Color = c;
}
Here AreaOfTank() call base class constructor with the parameter r and h. That means Tank() constructor is called and it will initialize the value of Radius and Height in AreaOfTank(). So there is no need for AreaOfTank class to initialize these values. If AreaOfTank required an extra field, then the field should be unique from the called fields like Color. By using the base keyword, it becomes easier to initialize the objects of the base class without any conflict and it also provides an authority to call the constructor of a base class from the derived class and also save the time of re-writing the codes.
Similar Reads
Private Constructors in C#
Prerequisite: Constructors in C# Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members. The private constructor is always declared by using a private keyword. Key PointsIt is the implementatio
3 min read
C# | Constructor Overloading
Prerequisite: Constructors in C# It is quite similar to the Method Overloading. It is the ability to redefine a Constructor in more than one form. A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors w
8 min read
C# Constructors
Constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Constructors in C# are fundamental components of object-oriented programming. Like methods, It contains the collection of instructions that are executed at the time of Object c
5 min read
C# | Copy Constructor
A constructor that creates an object by copying variables from another object or that copies the data of one object into another object is termed as the Copy Constructor. It is a parameterized constructor that contains a parameter of the same class type. The main use of copy constructor is to initia
3 min read
C# Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a child class to inherit the properties from the superclass. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse
6 min read
C# | Inheritance in interfaces
C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.Important Points: If a class implements an interface, then it is nece
3 min read
C# Program For Hierarchical Inheritance
Inheritance is a basic aspect of object-oriented programming. A superclass, also known as a base class, is a class whose members are inherited, whereas a subclass, also known as a derived class, is a class that inherits from a superclass. They are also known as the parent and child classes, respecti
4 min read
Nested Classes in C#
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods (member function which defines actions) into a single unit. In C#, a user is allowed to define a class within another class. Such types of classes are known as nested c
7 min read
Invoking an overloaded constructor using this keyword in C#
Prerequisite : Constructors in C#C# provides a powerful keyword known as this keyword and this keyword has many usages. Here we use this keyword to call an overloaded constructor from another constructor.Important Points: When you use this keyword to call a constructor, the constructor should belong
3 min read
C# Program to Demonstrate the Static Constructor in Structure
A Structure is a well-defined data structure that can hold elements of multiple data types. It is similar to a class because both are user-defined data types and both contain a bunch of different data types. You can also use pre-defined data types. However, sometimes the user might be in need to def
2 min read