In this blog post, I’ll discuss about one of the concepts of Object Oriented Programming which is Inheritance.
Inheritance is a way of deriving a class from another class. In the other words, a class can inherit the fields and methods from other class.
Inheritance is one way of achieving code reuse. Here’s why, when you want to create a new class and some functionality in it has already in another class, you can derive your class to the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write the code again in your new class.
Subclass is the class that is derived from another class (also called extended class, derived class, or child class). This is more specific type of a class.
Superclass is the class from which a subclass is derived (also called parent class or base class).
In the picture above, Person class is the superclass of Student class and Employee class. On the other hand, Student class and Employee class are the subclasses of Person class. Student and Employee is a more specific type of a Person.
Look at the class diagram above, notice that the Student class and Employee has no basic fields like firstName, lastName, lastName and age. It is because those fields are already inherited from the Person class. However, you can also declare those fields again with the same name in the subclass, thus, you are hiding the fields in the superclass (it can cause confusion and it is not recommended).
Not only the fields are inherited but also the methods (except for private methods) of the Person class. The methods eat() and sleep() of Person is inherited in the Student and Employee class.
You can add fields and methods to the subclass. In the case above, Student has a course and yearLevel fields and a study() method and Employee has salary and designation fields and a raiseSalary(int percent) method. By adding those fields and methods, you are extending the functionality of the class and that what makes the subclass more specific type.
You can change the behavior of the superclass by overriding it. Override a method by define a method with the same method signature, a method signature is the method name and the number and type of its parameters. Return types are not considered to be a part of the method signature.
If you liked this post, don’t forget to subscribe to this blog for more updates.