Garima Agrawal
Garima Agrawal

Reputation: 61

Use of derived class over the existing classes - Inheritance

Why do we need inheritance concept when we can simply instantiate another object in the existing class? For example: class Person { } class Student extends Person { }

Here the class student and person possess IS-A relationship. But what is the need to define student class when we can add the same functionality to Person class?

Upvotes: 2

Views: 69

Answers (2)

Jerrybibo
Jerrybibo

Reputation: 1325

Why do we need the concept of inheritance?

You're practically asking the question "Why bother with OOP when you can just code imperatively?"

It really comes down to a matter of coding practice/paradigm choice and as @ammaro stated, in this specific scenario, by utilizing inheritance you are able to not only refactor your code in a much cleaner and more organized way, but also are following proper object-oriented programming practices by doing so.

Theoretics aside and in practice, the reason why that you would need to define the Student class is that it has properties of and is based off the Person class, but it has other features that distinguishes it and thus should be created separately.

Hope this helped!

Upvotes: 1

Ammaro
Ammaro

Reputation: 380

The simple answer is code reuse.

Imagine that we have also the following classes: Employee, Child, Manager, Student, etc. What if we wanted to add some functionalities that are common to all these classes, like: name, surname, birthdate? We would have to add it to every class in our code.

This is where class inheritance helps us reuse our code: 1. We can create a class that is common to other classes. In this case a class called Person. 2. Make other classes (Employee, Student) inherit from this class

It has also other advantages. For instance, if we have a method that take an object of type Person, then it would work for objects whose class inherits from the class Person.

Upvotes: 3

Related Questions