^

Inheritance

Inheritance is one of the most important feature of object oriented programming. Using inheritance, you can create new classes from existing classes. The newly created class is known as or sub class and the existing class is known as base class or super class. Derived class inherits all the fi elds and methods from base class and adds its own elements. Inheritance relations among diff erent classes is called inheritance hierarchy or class hierarchy. Classes at higher level in the hierarchy are generalized classes and classes at lower levels are specialized classes.
  • java.lang.Object class is on the top of any java class hierarchy. Every
  • class in Java, whether user defi ed class or library class, inherits java.lang.Object class implicitly.

Is-a Relationship

Inheritance represents is-a relationship inheritance hierarchy:
real java inheritance
According to above inheritance hierarchy SavingAccount and CurrentAccount classes inherit class Account. The base hierarchy shows is-a relationship. It means that an object of SavingAccount class is an object of Account class. The is-a relationship is not applicable on SavingAccount and CurrentAccount classes because the object of SavingAccount class is not an object of CurrentAccount class.

Code Re-usability

One of the major benefi ts of inheritance is code reusability. It means that all methods of a class can be reused in other classes without rewriting them. As the following inheritance hierarchy (fi gure-2) depicts, class Commo contains a method getSquare(), which can be used by derived classes Circle and Cylinder to calculate area and volume, respectively.
inheritance re-usabiltiy

Using keyword extends

In Java programs, inheritance relation between classes can be established using keyword extends.
Syntax:
           class base
                 {
                   :
                 }
           class derived extends base
                 {
                    :
                 }
Implementation
class Common
    {
	double Pi = 3.14;
	double getSquare(double R)
	    {
		return(R*R);
   	    }
     }
class Circle extends Common
    {
	void area(double R)
	     {
	     	double ar = Pi * getSquare(R);
		System.out.println(“area = ” + ar);
	     }
     }
class Cylinder extends Common
    {
	void volume (double r, double h )
	    {
		double vol = Pi * getSquare(r) * h;
		System.out.println(“Volume of Cylinder = “ + vol);
	    }
    }
class IDemo
      {   public static void main(String args[])
	       {
		Circle c = new Circle();
			c.area(10.5);
		Cylinder cyl = new Cylinder();
			cyl.volume(12.5, 7.8);
	       }
      }
Explanation In this program, the method getSquare() is the member of class Common, which is used in Circle class for calculating area of circle (line 13) and in Cylinder class for calculating the volume of cylinder (line 21).

Types of Inheritance

In Java, inheritance can be of 4 types:

  1. Single level inheritance
  2. Multilevel inheritance
  3. Hierarchical inheritance
  4. Hybrid inheritance
Note:Multiple inheritance using classes is not allowed in Java.
  1. Single Level Inheritance
  2. Single level inheritance takes place when there are only two classes, one is base and the other one is derived, as shown below
    real java inheritance single level
  3. Multilevel Inheritance
  4. When a derived class becomes base for another class, then multilevel inheritance takes place, as shown below:
    real java inheritance multi level
  5. Hierarchical Inheritance
  6. In hierarchical inheritance, a single class becomes base for multiple subclasses, as shown below:
    real java inheritance hierarchical level
  7. Hybrid Inheritance
  8. Hybrid inheritance is a combination of multiple types of inheritance, as shown
    real java inheritance hybrid level

Method Overriding

You are already familiar with the fact that a derived (sub class) class inherits all the non private methods and variables of super class (base class). But sometimes, you want to change the behavior of a method inherited from the base class. In this situation, you will have to rewrite the method body by keeping the same signature (here, by signature we mean the name of the method), number of parameters, their types and their sequence should be same. This is exactly what is called
method overriding.
Whenever the method is invoked using the object of derived class, the ovrerridden in the derived class executes. Some rules for method overriding are listed below:
  • The name of the method, number of parameters, types and their order of appearance should be same as the method to be overridden from super class.
  • A final method of super class can not be overridden.
  • A method of super class having higher level of accessibility can not be overridden by the method having lower level of accessibility. For example, a public method cannot be overridden by a protected or private method. But a protected or a private method can be overridden by public method.

To understand more clearly, consider the following method of a super class
real java method overriding
Some valid and invalid overriding styles of this method are listed below:
Overriding in Subclass Validity Why
public int job (int i, fl oat f, String s) Valid Same Signature
protected int job (int i, fl oat f, String s) Invalid Less accessibility
public fl oat job (int i, fl oat f, String s) Invalid Diff erent Return type
public int job (int i, fl oat f) Invalid less parameters
public int job (fl oat f, int i, String s) Invalid Parameter types are in diff erent order
public int job (int x, fl oat f, String t) Valid Same signature
A static method can not be overridden as a non-static method. However, it must
qualify as static. If the overridden method has a throws clause in its declaration and if the overriding method also has a throws clause then the exceptions included in throws clause list must be either one of the exceptions in the throws clause list of overridden method or a subclass of it Note:The above point is applicable for checked exceptions only. However, it does not matter for unchecked exceptions The following code sample demonstrates the treatment of checked exceptions using throws clause while overriding a method.
class B
   {
      void readFile()throws FileNotFoundException
	     {
	         // Overridden method
             ------------
              -----------
		}
    }
class D extends B
   {
      void readFile() throws FileNotFoundException
	     {
	         // Overriding method
                -------------
        	-------------
	     }
    }
The above syntax is error free but if you remove throws
FileNotFoundException from overridden method (readFile()), it
causes compilation error.
If the overridden method has throws clause, the overriding method can skip the throws clause (applicable for checked exceptions only).
class B
      { void readFile()throws FileNotFoundException
	         {	  // Overridden method
		         -------------
	         }
      }
   class D extends B
     {     void readFile()
	{
	    // Overridden method
		--------------			
	}
   }
The above syntax is error free, even though throws clause is not used while overriding the method.

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap