A Project Repository for Inheritance Byte in Java
- Why is it useful? - It helps separate out common functionality and fields so that they can be reused across many other classes cleanly. Avoids code redundancy.
- Where to apply? - In the code base when different objects need to share common fields and functionality.
- How to apply? - Define a parent class with all shared functionalities & child classes that inherit these from the parent class.
- What is the drawback if we don’t use inheritance? - Code duplication, Higher maintenance cost.
-
Single inheritance
-
Multiple inheritance
-
Hierarchical inheritance
-
Multilevel inheritance
-
Hybrid inheritance
- Java Collections is a good example of application of inheritance.
- Java Exceptions is among one of the notable Class hierarchies displaying the effective use of inheritance.
- A class (child class) can extend another class (parent class) by inheriting its features.
- Implements the DRY (Don’t Repeat Yourself) programming principle.
- Improves code reusability.
- Composition is another way to reuse code from another class. It is achieved by creating a class containing instances of other classes that implement the desired functionality, rather than inheritance from a base or parent class.
- Further Reading:- Inheritance Vs Composition (veerpalbrar.github.io)
- Encapsulation and Abstraction are helpful to develop and maintain a big codebase.
- When there are similar objects in this big codebase that share common functionality, the common functionality and fields can be separated out into a separate base class which is then inherited by child classes.