Inheritance and its advantages in Java

An object is an instance of a class, which is a blueprint to create objects. You can create multiple objects from the same class. However, instead of programming from scratch, you can derive a class from another class. If you do so, your class, called a subclass, inherits the state (variables) and the behavior (methods) of the class from which it is derived. The class from which you derive your class is called the superclass. The property of inheriting the state and behavior of the superclass is called inheritance

In your subclass, you can override the inherited methods, and also write new methods and declare new variables. Furthermore, you are not limited to just one layer of inheritance. You can create a whole tree of inheritance, called a class hierarchy, as deep as needed. The methods and variables are inherited down through the levels. The rule of thumb for building the class hierarchy is: the farther down in the hierarchy a class appears, the more specialized its behavior is. 

There are some built-in classes in the Java language organized into a hierarchy tree, and the Object class is at the top of this class hierarchy. Also, each class that you write automatically becomes a subclass of the Object class even if you do not explicitly derive it from the Object class. The Object class provides some methods representing the behaviors that are common to all the objects created from different classes.

Remember that Unlike C++, Java offers only single inheritance; that is, a class can be directly derived only from one superclass.



The main advantages of inheritance are described here:

• Code reusability: Inheritance automates the process of reusing the code of the superclasses in the subclasses. With inheritance, an object can inherit its more general properties from its parent object, and that saves the redundancy in programming.


• Code maintenance: In any discipline, knowledge is made more manageable by hierarchical classification. Organizing code into hierarchical classes makes its maintenance and management easier.


• Implementing OOP: Inheritance helps to implement the basic OOP philosophy to adapt computing to the problem and not the other way around, because entities (objects) in the real world are often organized into a hierarchy. For example, in addition to their own specifics, all different specific students in your class share the properties of what is called a student, all the different specific employees at your workplace share the properties of what is called an employee, and so on.



Reference(s): SCJP Exam for J2SE 5

No comments:

Post a Comment