We will be starting off in this article talking about Inheritance as I believe it is the foundation of Object Oriented Programming. Just like the name implies inheritance is about passing on the rights and properties from one person to another. This is the exact same meaning in Programming. It is passing the properties of one class to another. The class that is giving out properties is called the base class while the class that inherits these properties is called the derived class.
To inherit from a class, we use the(:)symbol.
Let's see the example below.
If we are building our social media app and we have two classes one class has all the properties of the user and the second class is the message class but we want the Message class to have all the properties of in the User class. All we have to do is inherit from the User Class.
public class User
{
public string UserName = "Gbenga Daniel"
public string FirstName {get; set;}
public string sendEmailtoUser ()
{
///logic to send mail.
return "Email Sent SuccessFully";
}
}
public class Message : User //////inheriting from the User Class all user properties can be accessed by Message class
{
public string messageSender {get; set;}
public string messageReceiver {get; set;}
}
you can see that all the properties of User and Message are in the messages object.Cool right?. Inheritance helps with code functionality and property re-usability it also speeds up implementation time. Normally if we wanted to add the properties (UserName) and (FirstName) in our Message class we would have had to recreate it in the Message class. Now imagine in a large application this would just mean rewriting the same property and functions multiple times thus making the code unnecessarily bulky. But inheritance has helped us use the properties of the User class across several components.
SEALED CLASS.
If you don't want other classes to inherit from a class, use the sealed keyword:
sealed class User
{
public string UserName {get; set;}
public string FirstName {get; set;}
public string sendEmailtoUser ()
{
///logic to send mail.
return "Email Sent SuccessFully";
}
}
If Message class tries to inherit from Users this error message pops.(Error:'Message': cannot derive from sealed type 'User')
public class Message :User //////Error:'Message': cannot derive from sealed type 'User'
{
public string messageSender {get; set;}
public string messageReceiver {get; set;}
}
In Summary
In conclusion inheritance enables properties of one class to be passed down to classes that derive from that class.
This helps in with code and property re-usability, code functionality and speeds up implementation time.
Top comments (0)