An Inheritance Example


The “inheritance concept” is grouped into two categories: To inherit from a class, use the extends keyword. The Java inheritance is demonstrated in the following example, which includes three classes namely Calculator, Increment, and Calculation. Using extends keyword, the Calculation inherits the method add of Increment class. In addition, the Calculation overrides the method inc of Increment class.

Calculator.java (inheritance)
// Java program to illustrate the concept of inheritance 
// Calculator class
public class Calculator {
  public static void main( String args[ ] ) {
    int a = Integer.parseInt( args[0] );
    int b = Integer.parseInt( args[1] );
    Increment   demo1 = new Increment( );
    Calculation demo2 = new Calculation( );
    System.out.println( demo1.inc( a ) );
    System.out.println( demo2.inc( a ) );
    System.out.println( demo2.multiply( a, b ) );
  }
}
// Base class
class Increment {
  // Increment class has one field.
  int z;
  // Increment class has two methods.
  public int inc( int x ) { return( x + 1 ); }
  public int add( int x, int y ) {
    for ( int i = 0; i < y; i++ )  x = inc( x );
    return( x );
  }
}
// Derived class
class Calculation extends Increment {
  // Calculation class has two methods.
  // inc overrides the inc in the superclass Increment.
  public int inc( int x ) { return( super.inc( x+1 ) ); }
  public int multiply( int x, int y ) {
    z = 0;
    if ( ( x != 0 ) && ( y != 0 ) ) {
      for ( int i = 0; i < Math.abs( y ); i++ )  z += add( x, 0 );
      if ( ( x < 0 && y > 0 ) || ( x > 0 && y < 0 ) )  z = -z;
    }
    return( z );
  }
}
shell> java Calculator    

Output:               Result:

When an object of Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass. The superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass. If you consider the above program, you can instantiate the class as given below. But using the superclass reference variable (demo in this case) you cannot call the method multiply, which belongs to the subclass Calculation:
     Increment demo = new Calculation( );
     demo.inc( a );
     demo.add( a, b );
     demo.multiply( a, b );      // Error
Note that a subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.




      The buyout deal was worth $9 billion to the company,    
      so, really, it was an offer we couldn’t refuse.