Saturday, January 20, 2024

Object Oriented Programming- 2- Inheritance

Inheritance is one of the fundamental attributes of object-oriented programming.

It allows you to define a child class that reuses (inherits), extends, or modifies the behavior of a parent class.

The class whose members are inherited is called the base class.

The class that inherits the members of the base class is called the derived class.

Note: Above content is from Microsoft Learning.


Creating classes for our programming real world problems is useful. But Inheritance on the other hand is very useful to solve many other programming real world problems and will let yuou create more efficient code.

Lets try this with practical example.

Requirement 1: You need to create a class to store notes

public class Note {

  public int Id {get; set;}

  public string Title {get; set;}

  public string Description {get; set;}

}

Requirement 2: You need to have Todo with status. Let's consider the Todo is a Note with a status

In this case, we can consider the Note as the base class and ToDo as the derived class.

The base class Note already have the title and description properties.

We just need the Status to be implemented.

So the solution is

public class ToDo: Note {

  public string Status {get; set;}

}

Here the ToDo class is inheriting Note, so it includes the properties Id, Title and Description.

Now lets try using this.

var note1 = new Note() { Id = 1, Title = "Learn C#", Description = "Learn C# with ASP.NET" };

var todo1 = new ToDo() { Id = 1, Title = "Learn C#", Description = "Learn C# with ASP.NET", Status = "Active" };

No comments:

Post a Comment

Object Oriented Programming- 2- Inheritance

Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to define a child class...