Creating a Subclass
C# is an object-oriented programming language, and one of the fundamental elements of object-oriented programming is inheritance. Inheritance allows one class (the subclass) to inherit the members of another class (the superclass). In this tutorial, we'll delve into the process of creating a subclass in C#.
Understanding Inheritance
Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of their parents. With inheritance, we can reuse the fields and methods of the existing class, enabling a hierarchical classification.
In terms of C#, the class that is inherited is called the base class or superclass, and the class that does the inheriting is called the derived class or subclass.
A subclass can have only one superclass, but a superclass may have multiple subclasses.
Creating a Subclass
To create a subclass, we use the :
symbol and then specify the superclass name. Let's consider a simple example where we have a Person
class (superclass), and we want to create a Student
class (subclass) that inherits from Person
.
Here's how we would define the Person
superclass:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Now, let's create a Student
subclass that inherits from Person
:
public class Student : Person
{
public string School { get; set; }
}
In this case, Student
is the subclass and Person
is the superclass. The Student
class inherits all the members (properties and methods) of the Person
class.
Accessing Superclass Members
Now that we've created a subclass, we can use the superclass members as if they were declared in the subclass. Here's an example:
Student student = new Student();
student.Name = "John";
student.Age = 20;
student.School = "XYZ University";
In this example, Name
and Age
are properties of the Person
class, but we can access them from the Student
class because Student
is a subclass of Person
.
Overriding Superclass Methods
In C#, a subclass can provide its own implementation of methods that are already provided by its superclass. This is done using the override
keyword. Here's an example:
public class Person
{
public virtual string GetInfo()
{
return "This is a person.";
}
}
public class Student : Person
{
public override string GetInfo()
{
return "This is a student.";
}
}
In this example, both Person
and Student
classes have a GetInfo
method. The GetInfo
method in the Person
class is marked with the virtual
keyword, which means that it can be overridden in any subclass. The GetInfo
method in the Student
class is marked with the override
keyword, which means that it provides a new implementation of the GetInfo
method.
That's it for creating a subclass in C#. Remember, inheritance allows us to reuse code, which is a key principle of object-oriented programming.