Inheritance

      The process of acquiring the members of one class to another class is called as Inheritance or Deriving the new class form the old class or the existing class is called as Inheritance. In this concept the derived class acquires all the features of the old/existing class from which it is derived. This inheritance is achieved in the java programming by the usage of extend keyword. Suppose when classA is inherited from classB, then classA is called as subclass and classB is called as super class/parent class. classA gets the copy of classB,which provides all its features. The following is a syntax to extend a class.
  • public class <class_name1> extends <class_name2>
The main advantage of inheritance in Java programming is that, a programmer reuses the code of the super class without rewriting it. So, the size of code becomes less and the programmer feels easy to write the code. Let us see a simple example:

Inheritance Example
Fig1: Inheritance Example
If you observe the above example, in the main method we have created an object to the sub class i.e., to the Hire class. By creating the object to the Hire class we are able to access the super class method using subclass object.

Generally when we create the object to the subclass we can inherit the properties of all its super classes. The following figure clarifies you.


Inheritance Example
Fig2: Inheritance example
As shown in the above figure, every class by default inherits the properties of Object class either directly or indirectly.


What exactly the JVM do in the above program is, It first checks for the method display() in Hire class as it is not found it moves to the super class and check for the method there. As the method is found there it executes it. If it is not found there it moves to object class and checks for the method.

Now, observe the following program..
Inheritance Example
Inheritance Example

Here, If you observe the above program, we are creating the object of subclass and storing it in the super class(Sample) reference variable "s". This program produces the following error message.

           

No comments:

Post a Comment